LeetCode 81. Search in Rotated Sorted Array II
原题链接在这里: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 <= r){ 10 int mid = l + (r - l) / 2; 11 if(nums[mid] == target){ 12 return true; 13 } 14 15 if(nums[mid] < nums[r]){ 16 if(nums[mid] <= target && target <= nums[r]){ 17 l = mid + 1; 18 }else{ 19 r = mid - 1; 20 } 21 }else if(nums[mid] > nums[r]){ 22 if(nums[l] <= target && target <= nums[mid]){ 23 r = mid - 1; 24 }else{ 25 l = mid + 1; 26 } 27 }else{ 28 r--; 29 } 30 } 31 32 return false; 33 } 34 }