zoukankan      html  css  js  c++  java
  • Leetcode: Search in Rotated Sorted 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.

    难度:88. 参看网上分析,与Search in Rotated Sorted Array II唯一的区别是这道题目中元素会有重复的情况出现。不过正是因为这个条件的出现,出现了比较复杂的case,甚至影响到了算法的时间复杂度。原来我们是依靠中间和边缘元素的大小关系,来判断哪一半是不受rotate影响,仍然有序的。而现在因为重复的出现,如果我们遇到中间和边缘相等的情况,我们就丢失了哪边有序的信息,因为哪边都有可能是有序的结果。假设原数组是{1,2,3,3,3,3,3},那么旋转之后有可能是{3,3,3,3,3,1,2},或者{3,1,2,3,3,3,3},这样的我们判断左边缘和中心的时候都是3,如果我们要寻找1或者2,我们并不知道应该跳向哪一半。解决的办法只能是对边缘移动一步,直到边缘和中间不在相等或者相遇,这就导致了会有不能切去一半的可能。所以最坏情况(比如全部都是一个元素,或者只有一个元素不同于其他元素,而他就在最后一个)就会出现每次移动一步,总共是n步,算法的时间复杂度变成O(n)。

    边缘之所以可以移动,是因为在边缘和中间相等的情况下,中间明确可知不等于target(否则已经返回了),那么边缘的元素也不等于target, 所以不考虑这个元素不会影响result.

     1 public class Solution {
     2     public boolean search(int[] A, int target) {
     3         if (A == null || A.length == 0) {
     4             return false;
     5         }
     6         int l = 0;
     7         int r = A.length - 1;
     8         while (l <= r) {
     9             int mid = (l + r) / 2;
    10             if (A[mid] == target) return true;
    11             else if (A[mid] > A[r]) {
    12                 if (target>=A[l] && target<A[mid]) {
    13                     r = mid - 1;
    14                 }
    15                 else {
    16                     l = mid + 1;
    17                 }
    18             }
    19             else if (A[mid] < A[r]) {
    20                 if (target>A[mid] && target<=A[r]) {
    21                     l = mid + 1;
    22                 }
    23                 else {
    24                     r = mid - 1;
    25                 }
    26             }
    27             else {
    28                 r--; // A[mid] == A[r], and we know A[mid] != target, so A[r] can be taken away, it does not influence the result
    29             }
    30         }
    31         return false;
    32     }
    33 }
  • 相关阅读:
    ThinkSNS+ PHP开发概述
    基础知识--封装、继承、多态、抽象
    读书笔记--《你在为谁工作》
    深入理解设计模式(终):总结--设计模式是药,没病就不要吃药
    深入理解设计模式(24):外观模式
    深入理解设计模式(23):代理模式
    深入理解设计模式(22):享元模式
    深入理解设计模式(21):组合模式
    深入理解设计模式(20):桥接模式
    深入理解设计模式(19):装饰模式
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3978972.html
Copyright © 2011-2022 走看看