Search in Rotated Sorted Array II
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k(0<=k<nums.length) such that the resulting array is [nums[k], nums[k+1],…, nums[n-1], nums[0], nums[1],…, nums[k-1]] (0-indexed). For example, [0, 1, 2, 4, 4, 4, 5, 6, 6, 7] might be rotated at pivot index 5 and become [4, 5, 6, 6, 7, 0, 1, 2, 4, 4].
Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
今天的每日一题,是一道中等难度的题,要求搜索旋转排序数组。题目大概是这样的:有一个数组nums,它是按照非降序排列的,而且里面可能会有重复元素,然后将这个数组旋转某个随机数,将它变成一个有一定规律的数组,然后输入这个数组,和一个目标数target 。让我们判断target是否在nums中。
哎,说到底这就是一个搜索问题嘛,先来直接遍历:
public class Solution {
public boolean search(int[] nums, int target) {
for (int num : nums) {
if(num == target)
return true;
}
return false;
}
}
代码非常简单,结果也能通过
但是题目给了我们这么多的条件,当然不是希望我们以这种方法解决这个题的。
看了一下官方的题解,这道题是采用二分查找法来做的。
由于数组中可能会存在重复元素,所以可能会出现a[l] == a[mid] == a[r]这种情况,此时就无法判断哪一个区间是有序的了。对于这种情况,我们只能将左边界加一、右边界减一,然后在新区间上继续进行二分查找。
代码是这样的:
class Solution {
public boolean search(int[] nums, int target) {
int n = nums.length;
if (n == 0) {
return false;
}
if (n == 1) {
return nums[0] == target;
}
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) {
return true;
}
if (nums[l] == nums[mid] && nums[mid] == nums[r]) {
++l;
--r;
} else if (nums[l] <= nums[mid]) {
if (nums[l] <= target && target < nums[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
} else {
if (nums[mid] < target && target <= nums[n - 1]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
}
return false;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/sou-suo-xuan-zhuan-pai-xu-shu-zu-ii-by-l-0nmp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
嘶……这……怎么感觉好像还不如直接遍历呢。
不过嘛,我们做算法题就是为了学习新的算法思想嘛,主要是理解思想,只要理解了它,以后遇到更适合使用这个思想的题目的时候我们可以想起来用它,那我们这道题就算没白做。
ok,今天的每日一题完成√
算法题就是为了学习新的算法思想嘛,主要是理解思想,只要理解了它,以后遇到更适合使用这个思想的题目的时候我们可以想起来用它,那我们这道题就算没白做。
ok,今天的每日一题完成√