📌  相关文章
📜  在旋转排序数组中搜索 leetcode - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:44.205000             🧑  作者: Mango

代码示例1
class Solution {
    public int search(int[] nums, int target) {
        int pivot = FindPivot(nums);
        int a_pointer = 0;
        int b_pointer = nums.length-1;
        if (target >= nums[pivot] && target <= nums[b_pointer] ){
            a_pointer = pivot;
        }else{
            b_pointer = pivot;
        }
        if (nums[a_pointer] == target) return a_pointer;
        if (nums[b_pointer] == target) return b_pointer;
        while(a_pointer <= b_pointer){
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
            if (nums[midpoint] == target) return midpoint;
            if (nums[midpoint] < target) a_pointer = midpoint + 1;
            if (nums[midpoint] > target) b_pointer = midpoint - 1;
        }
        return -1;
    }
    
    public static int FindPivot(int[] nums){

        int start = 0;
        int end = nums.length-1;

        while (start < end){
            int mid = start + (end-start)/2;
            if (nums[mid] > nums[end]){
                start = mid+1;
            }else end = mid;
        }
        return start;
    }
}