Leetcode 81. 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.
解题思路:
与Leetcode Search in Rotated Sorted Array 类似。解题思路一致。只有重复数的差别。
当有重复数字,会存在A[mid] = A[end]的情况。此时右半序列A[mid-1 : end]可能是sorted,也可能并没有sorted,如下例子。
3 1 2 3 3 3 3
3 3 3 3 1 2 3
所以当A[mid] = A[end] != target时,无法排除一半的序列,而只能排除掉A[end]:
A[mid] = A[end] != target时:搜寻A[start : end-1]
正因为这个变化,在最坏情况下,算法的复杂度退化成了O(n):
序列 2 2 2 2 2 2 2 中寻找target = 1。
Java code:
public class Solution { public boolean search(int[] nums, int target) { int left = 0, right = nums.length-1; int index = -1; while(left <= right){ int mid = left + (right - left)/2; if(nums[mid] == target) { index = mid; } if(nums[mid] < nums[right]) { //right half sorted if(target > nums[mid] && target <= nums[right]){ left = mid+1; }else{ right = mid-1; } }else if(nums[mid] > nums[right]){ //left half sorted if(target >= nums[left] && target < nums[mid]){ right = mid-1; }else { left = mid+1; } }else{ right--; } } return index != -1; } }
2. 九章算法思路,本题与33题差异就在有相同的数字,那么最坏情况下,全部数字相等,那么复杂度就是O(n),每次只能扔掉一个数。还是比较start 和mid.
这次会有情况nums[start] == nums[mid] 那么就要去除一个数字 start 2016.01.15
public class Solution { public boolean search(int[] nums, int target) { int index = -1; if(nums == null || nums.length == 0) { return false; } int start = 0, end = nums.length-1; int mid; while(start + 1 < end){ mid = start + (end - start) / 2; if(nums[mid] == target) { index = mid; } if(nums[start] < nums[mid]){ if(nums[start] <= target && target <= nums[mid]){ end = mid; } else { start = mid; } } else if (nums[start] > nums[mid]){ if(nums[mid] <= target && target <= nums[end]){ start = mid; } else { end = mid; } } else { start++; } }//while if(nums[start] == target){ index = start; } if(nums[end] == target){ index = end; } return index != -1; } }
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leetcode-search-in-rotated-sorted-array.html