美文网首页
34. Find First and Last Position

34. Find First and Last Position

作者: 窝火西决 | 来源:发表于2019-06-10 21:17 被阅读0次

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]

题目

有序数组中找重复数字出现和结束的位置

思路

和33题很像,一样是二分法,这一次稍微简单点,如果nums[mid]=target,则两个独立的while一个往回找,一个往后找,找到边界,存储索引即可。

代码

public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        int l=0;
        int r=len-1;
        int ind1,ind2;
        int[] res = new int[2];
        while (l<=r) {
            int mid=(l+r)/2;
            if (nums[mid]==target) {
                ind1=mid;
                ind2=mid;
                while (ind1>=0&&nums[ind1]==target) {
                    ind1--;
                }
                while (ind2<=len-1&&nums[ind2]==target) {
                    ind2++;
                }
                res[0]=ind1+1;
                res[1]=ind2-1;
                return res;
            }else if (nums[mid]>target) {//证明得去左边找
                r=mid-1;
            }else {
                l=mid+1;
            }
        }
        if (l>r) {
            res[0]=-1;
            res[1]=-1;
        }
        return res;
    }

相关文章

网友评论

      本文标题:34. Find First and Last Position

      本文链接:https://www.haomeiwen.com/subject/czctfctx.html