您的位置:首页 > 其它

LeetCode Search in Rotated Sorted Array II

2015-11-11 22:17 477 查看
Description:

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.

Solution:

The solution is very similar to the former one, the only difference is that we need to differentiate the condition that nums[l] == nums[mid] and nums[r] == nums[mid], which requires that we need to l++ and r-- respectively.

<span style="font-size:18px;">import java.util.*;

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