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

    https://leetcode.com/submissions/detail/107115768/

    http://www.cnblogs.com/EdwardLiu/p/3978972.html

    Follow up for "Search in Rotated Sorted Array":
    What if duplicates are allowed?
    
    Would this affect the run-time complexity? How and why?
    Suppose an array sorted in ascending order 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).
    
    Write a function to determine if a given target is in the array.
    
    The array may contain duplicates.

    画图分情况讨论:

    根据1 增添之

    The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
    For example, 6 7 1 2 2 3 4 5 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half. But we should note that if the mid value is the same as endpoint. we should move only 1 step.

    public boolean search(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return false;
            }
            int beg = 0, end = nums.length - 1;
            while (beg + 1 < end) {
                int mid = beg + (end - beg) / 2;
                if (nums[mid] == target) {
                    return true;
                }
                if (nums[mid] > nums[end]) {
                    if (nums[mid] > target && nums[beg] <= target) {
                        end = mid;
                    } else {
                        beg = mid;
                    }
                } else if (nums[mid] < nums[beg]) {
                    if (nums[mid] < target && target <= nums[end]) {
                        beg = mid;
                    } else {
                        end = mid;
                    }
                } else if (nums[mid] == nums[end]) {
                    end--;
                } else  {
                    if (nums[mid] > target) {
                        end = mid;
                    } else {
                        beg = mid;
                    }
                }
            }
            if (nums[beg] == target) {
                return true;
            }
            if (nums[end] == target) {
                return true;
            }
            return false;
        }
    }
    

      

    以上方法和Search in Rotated Sorted Array是一样的,只是添加了中间和边缘相等时,边缘移动一步,但正是这一步导致算法的复杂度由O(logn)变成了O(n)。个人觉得在面试中算法复杂度还是很重要的考察点,因为涉及到对算法的理解,大家还是要尽量多考虑哈。  

      

  • 相关阅读:
    用两个栈实现队列(剑指09题)
    PHP 视频源文件加密方案
    PHP 实现大文件视频推流
    logstash笔记
    yum本地包的获取与安装
    IF.SVNAdmin安装 | SVN权限可视化管理
    Windows全局程序调用 Win + R
    Jenkins复制流水线命令行
    SVN hooks编写[Linux&Windows]
    AA压限, 语音识别去除语气词, 等
  • 原文地址:https://www.cnblogs.com/apanda009/p/7072811.html
Copyright © 2011-2022 走看看