33. Search in Rotated Sorted Array - Medium
阿新 • • 發佈:2018-12-04
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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
用binary search,迴圈終止條件是 l + 1 >= r(這樣的話最後需要判斷一下l 和 r 位置元素是否等於target)
由於陣列旋轉過,由兩部分遞增的序列組成。首先判斷l 和 m 所在元素的大小關係,如果[l, m]是遞增序列,進一步判斷target是否在該範圍中,並用binary search查詢target;如果nums[l] > nums[m],說明[l, m)不是遞增序列,而[m, r]是遞增序列,進一步判斷target是否在該範圍中,並用binary search查詢target。
時間:O(logN),空間:O(1)
class Solution { public int search(int[] nums, int target) { if(nums == null || nums.length == 0) return -1; int l = 0, r = nums.length - 1; while(l + 1 < r) { int m = l + (r - l) / 2; if(nums[m] == target)return m; if(nums[l] < nums[m]) { if(nums[l] <= target && target <= nums[m]) r = m; else l = m; } else { if(nums[m] <= target && target <= nums[r]) l = m; else r = m; } } if(nums[l] == target) return l; if(nums[r] == target) return r; return -1; } }