题目:
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.
题意:
继续上一题,如果有重复元素出现,那么该如何处理?还是如同上一题那么处理,采用二分搜索,然后考虑出现了重复的,那么就采用顺序遍历,知道找到了,否则就返回false.
public static boolean search(int[] nums, int target) {if(nums.length == 0 || nums == null)return false;int low = 0, high = nums.length - 1, mid;while(low <= high) {mid = low + (high - low) / 2;if(nums[mid] == target)return true;else if(nums[mid] > nums[low]) {if(target >= nums[low] && target < nums[mid])high = mid - 1;elselow = mid + 1;} else if(nums[mid] < nums[low]){if(target > nums[mid] && target <= nums[high])low = mid + 1;elsehigh = mid - 1;}else //如果是相等的情况,也就是说又重复,那么考虑顺序遍历{low++;} }return false;}