33. Search in Rotated Sorted Array I & II
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.
Example
For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
分析:
二分搜索。需要把升序部分和target进行比较。
1 public class Solution { 2 3 public int search(int[] A, int target) { 4 if (A == null || A.length == 0) return -1; 5 int left = 0, right = A.length - 1; 6 while (left <= right) { 7 int mid = left + (right - left) / 2; 8 if (A[mid] == target) { 9 return mid; 10 } else if (A[left] <= A[mid]) { // we have to use <= to handle the case in which we have [3, 1] and target is 1. 11 if (A[left] <= target && target < A[mid]) { 12 right = mid - 1; 13 } else { 14 left = mid + 1; 15 } 16 } else { 17 if (A[mid] < target && target <= A[right]) { 18 left = mid + 1; 19 } else { 20 right = mid - 1; 21 } 22 } 23 } 24 return -1; 25 } 26 }
Follow up for Search in Rotated Sorted Array:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Example
Given [1, 1, 0, 1, 1, 1] and target = 0, return true.
Given [1, 1, 1, 1, 1, 1] and target = 0, return false.
分析:
用一个方法来确定其中的一半是否单调递增。
1 class Solution { 2 public boolean search(int[] nums, int target) { 3 int start = 0, end = nums.length - 1; 4 5 //check each num so we will check start == end 6 //We always get a sorted part and a half part 7 //we can check sorted part to decide where to go next 8 while(start <= end){ 9 int mid = start + (end - start)/2; 10 if(nums[mid] == target) return true; 11 12 //if left part is sorted 13 if(nums[start] < nums[mid]){ 14 if(nums[start] <= target && target < nums[mid]){ 15 end = mid - 1; 16 }else{ 17 //target is in rotated part 18 start = mid + 1; 19 } 20 }else if(nums[start] > nums[mid]){ 21 //right part is sorted 22 //target is in rotated part 23 if(target > nums[mid] && target <= nums[end]){ 24 start = mid + 1; 25 }else{ 26 end = mid -1; 27 } 28 }else{ 29 //duplicates, we know nums[mid] != target, so nums[start] != target 30 //based on current information, we can only move left pointer to skip one cell 31 //thus in the worest case, we would have target: 2, and array like 11111111, then 32 //the running time would be O(n) 33 start++; 34 } 35 } 36 37 return false; 38 } 39 }

浙公网安备 33010602011771号