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 的变形。在上一题中数组中没有重复元素,我们用二分法,通过对比每次都可以删掉一般的元素,那样搜索的时间复杂度为O(logn)。在这一道题目中存在重复元素,在判断target可能再哪个区间的时候,就需要多一个判断,如果中间的元素与最左边或最右边的元素相等的时候,我们要单独处理。假设我们用二分法查找,中间元素nums[m]和target不相等,这时我们应该判断target可能在哪个区间,通过中间元素nums[m]与最左边的元素nums[i]相比,如果nums[m]与nums[left]不相等,那么处理的过程和上一道题目一样,如果nums[m] == nums[left],我们可以让left指针向左移动一个位置,然后继续查找,知道遇到nums[m] != nums[left]的情况。这样如果一个长度为n的数组中所有的元素都相等,这时的时间复杂度就为O(n)。所以对于这道题的时间复杂度最坏情况为O(n)。代码如下:
public class Solution { public boolean search(int[] nums, int target) { if(nums == null || nums.length == 0) return false; int l = 0; int r = nums.length - 1; while(l <= r) { int m = l + (r - l) / 2; if(target == nums[m]) return true; if(nums[m] < nums[l]) { if(target > nums[m] && target <= nums[r]) { l = m + 1; } else { r = m - 1; } } else if(nums[m] > nums[l]){ if(target >= nums[l] && target < nums[m]) { r = m - 1; } else { l = m + 1; } } else { l ++; } } return false; } }