zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array II

    Suppose a sorted array is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
    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.

     1 class Solution {
     2 public:
     3     bool search(int A[], int n, int target) {
     4         return search(A, 0, n-1, target);
     5     }
     6     bool search(int A[], int i, int j, int target) {
     7         if(i > j) return false;
     8         int mid = i + (j-i)/2;
     9         if(A[mid] == target) return true;
    10         if(A[i] < A[mid]) {
    11             if(target >= A[i] && target < A[mid])
    12                 return search(A, i, mid-1, target);
    13             else {
    14                 return search(A, mid+1, j, target);
    15             }
    16         }
    17         else if(A[i] > A[mid]) {
    18             if(target > A[mid] && target <= A[j]) 
    19                 return search(A, mid+1, j, target);
    20             else {
    21                 return search(A, i, mid-1, target);
    22             }
    23         }
    24         else {
    25             return search(A, i+1, mid-1, target) || search(A, mid+1, j, target);
    26         }
    27     }
    28 };
    29 
    30 // linear search
    31 class Solution {
    32 public:
    33     bool search(int A[], int n, int target) {
    34         for (int i = 0; i < n; i++)
    35             if (A[i] == target)
    36                 return true;
    37         return false;
    38     }
    39 };
  • 相关阅读:
    syslog命令
    linux命令 info
    Alibaba(阿里) RocketMQ入门实例
    java基础-学java util类库总结
    java 23种设计模式教程
    Linux
    Scrapy框架
    MongoDB的安装与使用
    爬虫小案例——爬取天猫
    爬虫小案例——爬取豆瓣电影
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646408.html
Copyright © 2011-2022 走看看