Find the first element in the array and sorting the last

Nums Given an array of integers arranged in ascending order, according to the target and one target value. Identify a given target start and end positions in the array.

Your time complexity of the algorithm must be O (log n) level.

If the target is not present 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]

answer:

public int[] searchRange(int[] nums,int target){
        int[] res={-1,-1};
        if(nums!=null&&nums.length>0){
            int _0=-1;
            int _1=-1;
            int lo=0;
            int hi=nums.length-1;
            while (lo<=hi){
                int mid=(lo+hi)/2;
                if(nums[mid]>target){
                    hi=mid-1;
                }else if(nums[mid]<target){
                    lo=mid+1;
                }else{
                    int turnLeft=mid;
                    int turnRight=mid;
                    while (turnLeft>=lo||turnRight<=hi){
                        if(_0>-1&&_1>-1){
                            break;
                        }
                        if(_0==-1&&(turnLeft>=lo&&(turnLeft-1)>=0&&nums[turnLeft-1]!=target)||(turnLeft==lo&&nums[turnLeft]==target)){
                            _0=turnLeft;
                        }
                        if(_1==-1&&(turnRight<=hi&&(turnRight+1)<nums.length&&nums[turnRight+1]!=target)||(turnRight==hi&&nums[turnRight]==target)){
                            _1=turnRight;
                        }
                        turnLeft--;
                        turnRight++;
                    }
                    res[0]=_0;
                    res[1]=_1;
                    break;
                }
            }
        }
        return res;
    }
View Code

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array

Guess you like

Origin www.cnblogs.com/wuyouwei/p/11936025.html