原题链接在这里:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
题目:
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.
题解:
是Search in Rotated Sorted Array的变形。与Find Minimum in Rotated Sorted Array 和 Find Minimum in Rotated Sorted Array II的关系十分相似。
加上了duplicates, 使得原有的通过nums[mid] 和 边界值 如nums[r]的大小关系判断前后两部分那部分带有rotation的方法不再有效。e.g. 若是nums[mid] == nums[r]此时不知道前后两部哪一部分有rotation. 所以此时只能移动边界, 如 r--. 所以worst case 是全部相同, 此时Time Complexity O(n).
其他情况若是 nums[mid] 和 nums[r] 不相同,就能判断出前后哪一部分有rotation, 剩下的与Search in Rotated Sorted Array相同。
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public boolean search(int[] nums, int target) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 7 int l = 0; 8 int r = nums.length-1; 9 while(l+1 < r){ 10 int mid = l+(r-l)/2; 11 if(nums[mid] < nums[r]){ 12 if(target>=nums[mid] && target<=nums[r]){ 13 l = mid; 14 }else{ 15 r = mid; 16 } 17 }else if(nums[mid] > nums[r]){ 18 if(target>=nums[l] && target<=nums[mid]){ 19 r = mid; 20 }else{ 21 l = mid; 22 } 23 }else{ 24 r--; 25 } 26 } 27 28 if(nums[l] == target || nums[r] == target){ 29 return true; 30 }else{ 31 return false; 32 } 33 } 34 }