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.

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

Follow up: Could you write an algorithm with O(log n) runtime complexity?

 

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

 

方法:

二分查找,分别找最小和最大位置

public int[] searchRange(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int begin = -1, end = -1;
        while (l <= r){
            int mid = l + (r - l) / 2;
            if (nums[mid] == target){
                if(begin == -1 || (begin != -1 && begin > mid)) begin = mid;
            }
            if (nums[mid]>=target) r = mid -1;
            else l = mid + 1;
        }
        l = 0;
        r = nums.length - 1;
        while (l <= r){
            int mid = l + (r - l) / 2;
            if (nums[mid] == target){
                if(end == -1 || (end != -1 && end < mid)) end = mid;
            }
            if (nums[mid]>target) r = mid -1;
            else l = mid + 1;
        }
        return new int []{begin, end};
        
    }

 

参考链接:

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

posted @ 2020-12-17 14:22  diameter  阅读(75)  评论(0编辑  收藏  举报