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

    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.

    Summary: Almost the same to Search in Rotated Sorted Array without duplicates, but careful about the corner case like [1311], we should search both left half and right half. So, in this case, the run-time complexity will between O(logN) to O(N).

     1 class Solution {
     2 public:
     3     bool search(int A[], int n, int target) {
     4         if(n == 0)
     5             return false;
     6         if(n == 1) {
     7             if(A[0] == target )
     8                 return true;
     9             else 
    10                 return false;
    11         }
    12         
    13         int median = n/2;
    14         if(A[median] == target)
    15             return true;
    16         if(A[0] == target)
    17             return true;
    18             
    19         if(A[0] < A[median] && target > A[0] && target < A[median] || 
    20             (A[0] > A[median] && (target > A[0] || target < A[median]))){
    21               return search(A + 1, median - 0, target);  
    22             }else if(A[0] == A[median]){
    23                 bool ret1 = search(A + 1, median - 0, target);      
    24                 bool ret2 = false;
    25                 if(n - median - 1 <= 0)
    26                     ret2 = false;
    27                 
    28                 ret2 = search(A + median + 1, n - median -1, target);
    29                 return ret1 || ret2;
    30             }else{
    31                 if(n - median - 1 <= 0)
    32                     return false;
    33                 
    34                 return search(A + median + 1, n - median -1, target);
    35             }
    36     }
    37 };
  • 相关阅读:
    Aras前端的一些知识
    Eclipse 实用快捷键大全
    Eclipse插件使用links目录的用法
    extjs portal 保存 事件
    NDRS SQL
    [VB]修改注册表让程序开机自动运行
    [C++]数组参数
    [C++]指针类型出参
    [C++]函数返回值
    [VBA]Excel输出utf8编码格式文件 使用WideCharToMultiByte
  • 原文地址:https://www.cnblogs.com/guyufei/p/3408347.html
Copyright © 2011-2022 走看看