算法34. Find First and Last Position of Element in Sorted Array

34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

class Solution {
    public int[] searchRange(int[] nums, int target) {
        
    }
}

说,给一个正序的整形数组,找到目标值得起始和结束的下标。
要求时间复杂度为O(logn)。
没找到就返回[-1,-1]。

解:
要求时间复杂度为O(logn),首先想到折半查找。折半呢,找一个数好找,找末尾呢,取个巧,找大于目标值+1的数的下标减一即可。以下为代码:

public int[] searchRange(int[] nums, int target) {
    int[] targetRange = { -1, -1 };

    int leftIdx = extremeInsertionIndex(nums, target);

    if (leftIdx == nums.length || nums[leftIdx] != target) {
        return targetRange;
    }

    targetRange[0] = leftIdx;
    targetRange[1] = extremeInsertionIndex(nums, target + 1) - 1;

    return targetRange;
}

private int extremeInsertionIndex(int[] nums, int target) {
    int lo = 0;
    int hi = nums.length;

    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (nums[mid] >= target) {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }

    return lo;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容