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;
        }
    };
    
  • 相关阅读:
    axis2调用webservice
    JSON: Property 'xxx' has no getter method的解决办法
    JDK中工具类的使用
    Java权限讲解
    JSON的使用
    策略模式
    Tomcat虚拟目录的设置
    extends 与 implements 的区别
    利用正则表达式分割字符串
    给面板添加背景图片
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7761089.html
Copyright © 2011-2022 走看看