内容简介:Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).You are given a target value to search. If found in the array return true, otherwise return false.
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. Would this affect the run-time complexity? How and why?
难度:medium
题目:假设一个按升序 排序 的数组在某个未知的轴上旋转。搜索给定目标值,如果找到返回true,否则返回false。
思路:二叉搜索。
分4种情况。
case 1:从头到尾升序。 case 2:从头到尾降序。 case 3:升序的元素多,降序少。 case 4:升序的元素少,降序多。
Runtime: 0 ms, faster than 100.00% of Java online submissions for Search in Rotated Sorted Array II.
Memory Usage: 37.6 MB, less than 1.00% of Java online submissions for Search in Rotated Sorted Array II.
class Solution {
public boolean search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target == nums[mid]) {
return true;
}
// left < mid </> right
if (nums[left] < nums[mid]) {
if (target > nums[mid] || target < nums[left]) {
left = mid + 1;
} else {
right = mid - 1;
}
} else if (nums[left] > nums[mid]) { // left > mid </> right
if (target < nums[mid] || target > nums[right]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else { // left = mid
left += 1;
}
}
return false;
}
}
以上所述就是小编给大家介绍的《81. Search in Rotated Sorted Array II》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
海量运维、运营规划之道
唐文 / 电子工业出版社 / 2014-1-1 / 59.00
《海量运维、运营规划之道》作者具有腾讯、百度等中国一线互联网公司多年从业经历,书中依托工作实践,以互联网海量产品质量、效率、成本为核心,从规划、速度、监控、告警、安全、管理、流程、预案、考核、设备、带宽等方面,结合大量案例与读者分享了作者对互联网海量运维、运营规划的体会。 《海量运维、运营规划之道》全面介绍大型互联网公司运维工作所涉及的各个方面,是每个互联网运维工程师、架构师、管理人员不可或......一起来看看 《海量运维、运营规划之道》 这本书的介绍吧!