[LeetCode] 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.

这道是之前那道 Search in Rotated Sorted Array 在旋转有序数组中搜索 的延伸,现在数组中允许出现重复数字,这个也会影响我们选择哪半边继续搜索,由于之前那道题不存在相同值,我们在比较中间值和最右值时就完全符合之前所说的规律:如果中间的数小于最右边的数,则右半段是有序的,若中间数大于最右边数,则左半段是有序的。而如果可以有重复值,就会出现来面两种情况,[3 1 1] 和 [1 1 3 1],对于这两种情况中间值等于最右值时,目标值3既可以在左边又可以在右边,那怎么办么,对于这种情况其实处理非常简单,只要把最右值向左一位即可继续循环,如果还相同则继续移,直到移到不同值为止,然后其他部分还采用 Search in Rotated Sorted Array 在旋转有序数组中搜索 中的方法,可以得到代码如下:

class Solution {
public:
    bool search(int A[], int n, int target) {
        if (n == 0) return false;
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (A[mid] == target) return true;
            else if (A[mid] < A[right]) {
                if (A[mid] < target && A[right] >= target) left = mid + 1;
                else right = mid - 1;
            } else if (A[mid] > A[right]){
                if (A[left] <= target && A[mid] > target) right = mid - 1;
                else left = mid + 1;
            } else --right;
        }
        return false;
    }
};

本文转自博客园Grandyang的博客,原文链接:在旋转有序数组中搜索之二[LeetCode] Search in Rotated Sorted Array II ,如需转载请自行联系原博主。

相关文章
|
1月前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
3月前
|
机器学习/深度学习 C语言
LeetCode | 17.04.消失的数字和189.旋转数组
17.04.消失的数字 OJ链接 这里题目要求在时间复杂度上O(n)我们介绍三种方法,看看哪种方法适合这道题~~
|
3月前
|
Go
golang力扣leetcode 240.搜索二维矩阵II
golang力扣leetcode 240.搜索二维矩阵II
19 0
|
3月前
|
Go
golang力扣leetcode 79.单词搜索
golang力扣leetcode 79.单词搜索
25 0
|
3月前
|
机器学习/深度学习
leetcode-48:旋转图像
leetcode-48:旋转图像
21 0
|
1月前
|
机器学习/深度学习 人工智能 算法
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
|
1月前
|
存储 算法
LeetCode刷题--- 61. 旋转链表(快慢指针+闭合为环)
LeetCode刷题--- 61. 旋转链表(快慢指针+闭合为环)
|
3月前
|
算法
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
|
3月前
|
Go
golang力扣leetcode 48.旋转图像
golang力扣leetcode 48.旋转图像
17 0
|
3月前
|
Go
golang力扣leetcode 396.旋转函数
golang力扣leetcode 396.旋转函数
22 1

热门文章

最新文章