zoukankan      html  css  js  c++  java
  • LeetCode——search-in-rotated-sorted-array-ii

    Question

    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.

    Solution

    1. 暴力求解,时间复杂度O(n)

    2. 二分查找。虽然是旋转数组,但是总有一部分是有序的,我们可以直接判断目标是否在有序的那一部分,如果不在,那么就在另外一部分。先判断左半部分是否有序。

    3. 因为考虑到首、尾、中间值,可能都相同的情况,比如11101和10111,0可能在左边也也可能在右边,这个时候只能依次遍历。

    4. 时间复杂度O(lgn)

    Code

    class Solution {
    public:
        bool search(int A[], int n, int target) {
            int i = 0;
            int j = n - 1;
            while (i <= j) {
                int mid = (i + j) >> 1;
                if (A[mid] == target)
                    return true;
                // 必须依次查找
                if (A[i] == A[mid] && A[mid] == A[j]) {
                    for (int k = i; k <= j; k++) {
                        if (A[k] == target)
                            return true;
                    }
                    return false;
                }
                if (A[i] <= A[mid]) {
                	// 判断是否在左边有序的部分里面,不在就在另外一部分
                    if (target >= A[i] && target <= A[mid])
                        j = mid - 1;
                    else
                        i = mid + 1;
                } else if (A[mid] <= A[j]) {
                	// 判断是否在右边有序的部分里面,不在就在另外一部分
                    if (target >= A[mid] && target <= A[j])
                        i = mid + 1;
                    else
                        j = mid - 1;
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    Python从入门到精通系列文章总目录
    使用465端口加密发邮件
    kubernetes学习14—Dashboard搭建和认证
    kubernetes学习01—kubernetes介绍
    CSS基础
    SVN 命令行的使用
    Python判断字符集
    Flask框架(2)-JinJa2模板
    搭建ntp服务器
    Ansible的Playbook的编写
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7761089.html
Copyright © 2011-2022 走看看