1. 程式人生 > >LC.33. Search in Rotated Sorted Array

LC.33. Search in Rotated Sorted Array

ota ont style 變化 sort not sea otherwise img

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)


 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 { 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 }

技術分享圖片

技術分享圖片

LC.33. Search in Rotated Sorted Array