• [LeetCode] Search in Rotated 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.

    思路:本题思路和http://www.cnblogs.com/vincently/p/4122528.html类似。只是如果有重复的话就不能依靠与边界的比较确定递增的序列。例如,[1,3,1,1,1],对于A[m]>=A[l]来说,[l,m]的假设就不成立。但是还是可以观察到,左边子数组的值都要大于等于右边子数组的值。将A[m]>=A[l]拆分为两种情况:A[m]>A[l],则区间[l,m]一定递增;如果 A[m]==A[l]确定不了,那就l++,往下看一步。

    时间复杂度改变为O(n),空间复杂度O(1)

     1 class Solution {
     2 public:
     3     bool search(int A[], int n, int target) {
     4         int first = 0, last = n - 1;
     5         while (first <= last) {
     6             const int mid = low + ((high - low) >> 1);
     7             if (A[mid] == target) return true;
     8             if (A[first] < A[mid]) {
     9                 if (A[first] <= target && target < A[mid])
    10                     last = mid - 1;
    11                 else
    12                     first = mid + 1;
    13             } else if (A[first] > A[mid]){
    14                 if (A[mid] < target && target <= A[last])
    15                     first = mid + 1;
    16                 else 
    17                     last = mid - 1;
    18             } else {
    19                 first++;
    20             }
    21         }
    22         return false;
    23     }
    24 };
  • 相关阅读:
    node作为反向代理服务器
    引擎模板jade常见用法
    express4中模板引擎ejs
    express4+mysql博客项目
    关于zepto需要注意的地方
    css中需要注意的地方
    typescript基础类型
    vue全文搜索高亮显示
    js搜索全文高亮显示
    js随机验证码
  • 原文地址:https://www.cnblogs.com/vincently/p/4122676.html
Copyright © 2020-2023  润新知