zoukankan      html  css  js  c++  java
  • 乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array

    乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array

    一、前言

        这次我们还是要改造二分搜索,但是想法却有一点不一样。

    二、Find First and Last Position of Element in Sorted Array

    2.1 问题

    2.2 分析与解决

       查找问题,时间复杂度要求对数级别的,我们自然的想到了二分查找,和上一题一样,需求都是有点不一样的,这次是有重复的数字,找出某一特定的重复的数组的起始和结束位置,我们依旧要是有二分查找,不过,当找到了目标值的时候,不能直接返回,需要判断这个数值的左右是否有同样的数字,如果左右都有,则继续左右搜索,如果左有右没有则记录结束为止并且向左搜索,如果右有左没有,则记录左节点并且向右搜索。

    class Solution {
        // returns leftmost (or rightmost) index at which `target` should be
        // inserted in sorted array `nums` via binary search.
        private int extremeInsertionIndex(int[] nums, int target, boolean left) {
            int lo = 0;
            int hi = nums.length;
    
            while (lo < hi) {
                int mid = (lo + hi) / 2;
                if (nums[mid] > target || (left && target == nums[mid])) {//这一句非常重要
                    hi = mid;
                }
                else {
                    lo = mid+1;
                }
            }
    
            return lo;
        }
    
        public int[] searchRange(int[] nums, int target) {
            int[] targetRange = {-1, -1};
    
            int leftIdx = extremeInsertionIndex(nums, target, true);
    
            // assert that `leftIdx` is within the array bounds and that `target`
            // is actually in `nums`.
            if (leftIdx == nums.length || nums[leftIdx] != target) {
                return targetRange;
            }
    
            targetRange[0] = leftIdx;
            targetRange[1] = extremeInsertionIndex(nums, target, false)-1;
    
            return targetRange;
        }
    }
    

     

    三、总结

        通过改造二分搜索,我们可以得到正确的答案,但是我们同样也看到了,算法的简练渡和通用性的重要意义。

  • 相关阅读:
    Python之socket
    Python之创建low版的线程池
    Python之面向对象及相关
    Python之面向对象(进阶篇)
    Python之面向对象(初级篇)
    Python之线程与进程
    python中执行父类的构造方法
    python之反射
    记一次有趣的米筐经历~
    算法第四章作业
  • 原文地址:https://www.cnblogs.com/zyrblog/p/10224279.html
Copyright © 2011-2022 走看看