LeetCode(33)Search in Rotated Sorted Array解題報告

2682 ワード

Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Subscribe to see which companies asked this question
public int search(int[] nums, int target) {
        int start,end,mid;
        start = 0;
        end = nums.length-1;
        while(start <= end){
            mid = (start+end) / 2;
            if(nums[mid] == target)
                return mid;
            else if(nums[start] < nums[mid]){
                if(nums[start] <= target && nums[mid] > target){
                    end = mid-1;
                }
                else{
                    start = mid+1;
                }
            }
            else if(nums[mid] < nums[end]){
                    if(nums[mid] < target && nums[end] >= target){
                        start = mid+1;
                    }
                    else{
                        end = mid-1;
                    }
            }
        }
        return -1;
    }