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)。个人觉得在面试中算法复杂度还是很重要的考察点,因为涉及到对算法的理解,大家还是要尽量多考虑哈。  

      

  • 相关阅读:
    快速幂 + 矩阵快速幂
    iOS 获取设备的 UDID,安装描述文件、证书
    自定义View 圆角的ImageView
    使用Glide设置view背景
    dp转px,sp转px
    Android注解约束参数为固定的某几个值
    SourceTree回滚远程仓库
    Android加载视频封面的两种方式
    Android Glide加载视频封面
    ios 关于如何在app里面设置版本更新功能
  • 原文地址:https://www.cnblogs.com/apanda009/p/7072811.html
Copyright © 2011-2022 走看看