您的位置:首页 > 其它

LeetCode 81. Search in Rotated Sorted Array II(搜索旋转的数组)

2016-05-22 05:30 756 查看
原题网址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

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 class Solution {
private boolean search(int[] nums, int target, int from, int to) {
if (from > to) return false;
if (from == to) return nums[from] == target;
int m = (from+to)/2;
if (nums[m] == target) return true;
if (nums[from] == nums[to]) return search(nums, target, from, m-1) || search(nums, target, m+1, to);
if (nums[from] < nums[to]) {
if (nums[m] < target) return search(nums, target, m+1, to);
else return search(nums, target, from, m-1);
}
// nums[from] > nums[to]
if (nums[from] <= nums[m]) {
if (nums[from] <= target && target < nums[m]) return search(nums, target, from, m-1);
return search(nums, target, m+1, to);
} else {
if (nums[m] < target && target <= nums[to]) return search(nums, target, m+1, to);
return search(nums, target, from, m-1);
}
//此处错误!!!
// if ((nums[from] <= target && target < nums[m]) || (target < nums[m] && nums[m] <= nums[to])) return search(nums, target, from, m-1);
// return search(nums, target, m+1, to);
}
public boolean search(int[] nums, int target) {
return search(nums, target, 0, nums.length-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: