Question:
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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.
Tips:
给定一个数组,该数组是由一个有序的数组经过旋转(即将前面一段数字接到整个数组之后)得到的。判断target是否存在于该数组之中。
本题为33题升级版本,数组中的数字可以出现重复,如果target存在,返回他的true不存在则返回false。
思路:
本题与33提相似,但是由于数组中存在重复数字,可能会出现low high mid三个数字均相等的情况,这时为了跳出相等数字,需要low++或者high--;
代码:
public boolean search(int[] nums, int target) { if (nums == null) return false; int low = 0; int len = nums.length; int high = len - 1; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == target) return true; if (nums[low] < nums[mid] || nums[mid]>nums[high]) { if (target < nums[mid] && target >= nums[low]) { high = mid - 1; } else low = mid + 1; }else if(nums[mid]<nums[high] || nums[low]>nums[mid]){ if(target<=nums[high] && target>nums[mid]){ low=mid+1; }else{ high=mid-1; } } else{ low++; } } return false; }