LC.33. Search in Rotated Sorted Array

 

https://leetcode.com/problems/search-in-rotated-sorted-array/description/
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.

time: o(logn) space: o(1)

Find Minimum in Rotated Sorted Array类似。因为rotate, 所以不能直接用Binary Search, 需要进行 二次判定。

case 1: nums[mid] == target, return mid.

case 2: nums[mid] < nums[r]. 此时说明 右侧是正常升序,没有rotation, 若是这种情况下 target > nums[mid] && target <= nums[r] 就在右侧查找,其他情况左侧查找。

case 3: nums[mid] > nums[r]. 此时说明 左侧是正常升序,没有rotation, 若是这种情况下 target < nums[mid] && target >= nums[l] 就在左侧查找,其他情况右侧查找

note here since there is no duplicate and the left + 1 = mid will exit, there wouldnt be a case that the nums[left]= nums[mid] or nums[mid] == num[right]
make sure also checks the LC.81

 1 public int search(int[] nums, int target) {
 2         if (nums == null || nums.length ==0 ) return -1 ;
 3         int left = 0, right = nums.length -1 ;
 4         while(left + 1 < right){
 5             int mid = left + (right-left)/2;
 6             if (nums[mid] == target) return mid ;
 7             //break into two parts: note, there is no duplicate
 8             //first half
 9             if (nums[left]< nums[mid] ){
10                 if (target<=nums[mid] && nums[left] <=target){
11                     right = mid ;
12                 }else {
13                     left = mid ;
14                 }
15             }
16             //second half:注意判断顺序进行改变
17             else if (nums[mid] < nums[right]){
18                 if (nums[mid]<=target && target <= nums[right]){
19                     left = mid ;
20                 }else {
21                     right = mid;
22                 }
23             }
24         }
25         //post processing for the left and right
26         if (nums[left] == target){
27             return left ;
28         }
29         if(nums[right] == target){
30             return right;
31         }
32         return -1 ;
33     }

 

 

 

 

 

 

posted @ 2018-02-25 09:49  davidnyc  阅读(132)  评论(0编辑  收藏  举报