Leetcode: Search in Rotated Sorted Array
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.
根据binary search,每次我们都可以切掉一半的数据,所以算法的时间复杂度是O(logn),空间复杂度是O(1)。
1 class Solution { 2 public int search(int[] nums, int target) { 3 if (nums == null || nums.length == 0) return -1; 4 int l = 0, r = nums.length - 1; 5 while (l <= r) { 6 int m = l + (r - l) / 2; 7 if (nums[m] == target) return m; 8 if (nums[m] >= nums[l]) { 9 // [l, m] is in order 10 if (nums[l] <= target && target < nums[m]) { 11 r = m - 1; 12 } 13 else l = m + 1; 14 } 15 else { 16 // [m, r] is in order 17 if (nums[m] < target && target <= nums[r]) { 18 l = m + 1; 19 } 20 else r = m - 1; 21 } 22 } 23 return -1; 24 } 25 }