33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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.

在旋轉了的有序數組裏面查找 


在正常的有序數組中 我們可以使用二分查找 是因爲整個數組是有序的 把數組從中間分開 仍然是兩個有序數組

旋轉了的有序數組 在旋轉點的前後 分別是有序數組 數組從中間分開 那麼至少有一個是有序數組 對於這部分 我們仍然可以採用二分查找


 public int search(int[] nums, int target) {
        int start = 0, end = nums.length-1;
        while (start <= end) {
            int mid = (start+end) >>> 1;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] >= nums[start]) {
                if (target >=nums[start] && target < nums[mid]) {
                    end = mid-1;
                } else start = mid+1;
            } else {
                if (target > nums[mid] && target <= nums[end]) {
                    start = mid+1;
                } else end = mid-1;
            }
        }
        return -1;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章