LeetCode 81.Search in Rotated Sorted Array II(M)
题目:
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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
思路:
1.当数组长度为0时,return false;
2.当数组长度为1时,比较nums[0]与target关系;
3.当数组长度大于1,且为rotated sorted array时,根据nums[mid]与nums[start]关系判断如何移动,见下图:
4.当数组长度大于1,但不是rotated sorted array时,用传统二分法。
代码:
1 public class Solution { 2 public boolean search(int[] nums, int target) { 3 int start = 0,end = nums.length-1,mid = 0; 4 if(nums.length == 0){ 5 return false; 6 } 7 if(nums.length == 1){ 8 if(nums[0] == target){ 9 return true; 10 }else{ 11 return false; 12 } 13 } 14 while(nums[start]>= nums[end] && start + 1<end){ 15 mid = start + (end - start)/2; 16 if(nums[mid] == target || nums[start] == target ||nums[end] == target ){ 17 return true; 18 }else if(nums[mid] > nums[start]){ 19 if(nums[mid] < target){ 20 start = mid; 21 }else if(nums[start] < target){ 22 end = mid; 23 }else if(nums[start] > target){ 24 start = mid; 25 } 26 }else if(nums[mid] < nums[start]){ 27 if(nums[mid] > target){ 28 end = mid; 29 }else if(nums[end] > target){ 30 start = mid; 31 }else if(nums[end] < target){ 32 end = mid; 33 } 34 }else{ 35 start++; 36 } 37 } 38 while(nums[start]< nums[end] && start + 1<end){ 39 mid = start + (end - start)/2; 40 if(nums[mid] == target){ 41 return true; 42 }else if(nums[mid] > target){ 43 end = mid; 44 }else if(nums[mid] < target){ 45 start = mid; 46 }else{ 47 start++; 48 } 49 } 50 if(nums[start] == target || nums[end] == target){ 51 return true; 52 } 53 return false; 54 } 55 }