您的位置:首页 > 其它

LeetCode Search in Rotated Sorted Array II

2015-07-12 20:57 316 查看

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.

题意:给出一个数组(有重复元素,是经过旋转的有序数组)及一个数,问这个数是否在数组中出现

思路:二分法

代码如下

第一种用递归(用时364ms)

public class Solution
{
private boolean check(int[] nums, int left, int right, int target)
{
int mid = (left + right) >> 1;
if (left > right) return false;

if (nums[mid] == target) return true;

return check(nums, left, mid - 1, target) || check(nums, mid + 1, right, target);
}

public boolean search(int[] nums, int target)
{
int left = 0, right = nums.length - 1;

return check(nums, left, right, target);
}
}

第二种非递归(用时388ms)

代码如下

public class Solution {

public boolean search(int[] nums, int target)
{
int left = 0, right = nums.length - 1;

while (left <= right)
{
int mid = (left + right) >> 1;
if (nums[mid] == target) return true;
else if (nums[left] == nums[mid] && nums[mid] == nums[right])
{
left++;
right--;
}
else if (nums[left] <= nums[mid])
{
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
}
else
{
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: