LeetCode 81 Search in Rotated Sorted Array II

·  阅读 153

LeetCode 81 Search in Rotated Sorted Array II

思路

二分查找。当nums[left] == nums[mid] && nums[right] == num[right]时,是无法确认下一步应该如何调整查找区间的,此时调整边界即可。此时有两种方案:

  1. 同时检查两个边界,nums[left] == nums[mid] && nums[mid] == nums[right]成立时,修改左右边界。

  2. 只检查一个边界,nums[left] == nums[mid]成立时,修改左边界。nums[left] == nums[mid] && nums[mid] == nums[right]同样不能成立,因为我们保证了nums[left] == nums[mid]一直为假。

nums[mid]是否等于target需要在nums[left] == nums[mid] && nums[right] == num[right]之前检查。如果在之后检查,在nums[left] == nums[mid] && nums[right] == num[right] && nums[mid] == target为true的情况下,将答案错过。也说明了,当mid指向的元素不等于target的时候,才考虑如何调整搜索区间。

代码

检查两个边界

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1, mid;
        
        while (left <= right) {
            mid = left + (right - left) / 2;
            
            if (nums[mid] == target) return true;
            
            if (nums[left] == nums[mid] && nums[mid] == nums[right]) {
                --right;
                ++left;
                continue;
            }
            
            if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && 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;
    }
};
复制代码

检查一个边界

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1, mid;
        
        while (left <= right) {
            mid = left + (right - left) / 2;
            
            if (nums[mid] == target) return true;
            
            if (nums[left] == nums[mid]) {
                ++left;
                continue;
            }
            
            if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && 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;
    }
};复制代码
分类:
阅读
标签:
分类:
阅读
标签:
收藏成功!
已添加到「」, 点击更改