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

      

  • 相关阅读:
    算法练习--ABCD*E=DCBA
    Android实现炫酷SVG动画效果
    swift -NavigationController,代理传值
    交换机的原理及其配置(一)
    NOI2015 题解
    实现存储过程详解
    数据流图(DFD)画法
    SQL SERVER 常用字符类型的区别
    数据库常见面试题集锦,数据库面试题,数据库练习题
    Django自定义模型(model)中的字段标签
  • 原文地址:https://www.cnblogs.com/apanda009/p/7072811.html
Copyright © 2020-2023  润新知