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

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

1、前言

    此次咱們仍是要改造二分搜索,可是想法卻有一點不同。java

2、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;
    }
}

 

3、總結

    經過改造二分搜索,咱們能夠獲得正確的答案,可是咱們一樣也看到了,算法的簡練渡和通用性的重要意義。數組

相關文章
相關標籤/搜索