您的位置:首页 > 其它

LeetCode 81 Search in Rotated Sorted Array II

2016-08-06 22:33 323 查看
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.

public boolean search2(int[] nums, int target) {
int low = 0, high = nums.length - 1, mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (nums[mid] == target) return true;
while (nums[mid] == nums[low] && mid > low) low++;
while (nums[mid] == nums[high] && high > mid) high--;
if (nums[mid] <= nums[high]) {//右边有序
if (nums[mid] < target && target <= nums[high]) low = mid + 1;
else high = mid - 1;
} else {//左边有序
if (nums[low] <= target && target < nums[mid]) high = mid - 1;
else low = mid + 1;
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode