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

      

  • 相关阅读:
    数据类型之集合
    数据类型之字典
    数据类型之元组
    数据类型之列表
    python基础之数据类型转换
    python基础之格式化输出
    python基础之运算符、if条件语句、while循环、for循环
    廖雪峰大神git学习笔记
    elementui记录
    从零开始创建一个react项目
  • 原文地址:https://www.cnblogs.com/apanda009/p/7072811.html
Copyright © 2011-2022 走看看