当前位置:网站首页>Topic35——34. Find the first and last positions of elements in a sorted array

Topic35——34. Find the first and last positions of elements in a sorted array

2022-06-23 06:37:00 _ Cabbage_

subject : Give you an array of integers in non decreasing order nums, And a target value target. Please find out the start position and end position of the given target value in the array .
If the target value does not exist in the array target, return [-1, -1].
You must design and implement a time complexity of O(log n) The algorithm to solve this problem .

 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]

 Example  3:
 Input :nums = [], target = 0
 Output :[-1,-1]

Tips :
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums It is a group of non decreasing numbers
-109 <= target <= 109

class Solution {
    
    public int[] searchRange(int[] nums, int target) {
    
        int[] res = new int[2];
        Arrays.fill(res, -1);
        if(nums.length == 0)
            return res;
        int l = 0;
        int r = nums.length;
        //  Look for the left border 
        while(l < r) {
    
            int mid = (l + r) / 2;
            if(nums[mid] == target) {
    
                r = mid;
            } else if (nums[mid] > target) {
    
                r = mid;
            } else if (nums[mid] < target) {
    
                l = mid + 1;
            }
            if(l >= r && l <= nums.length - 1 && nums[l] == target) {
    
                res[0] = l;
            }
        }
        l = 0;
        r = nums.length;
        //  Look for the right border 
        while(l < r) {
    
            int mid = (l + r) / 2;
            if(nums[mid] == target) {
    
                l = mid + 1;
            } else if (nums[mid] > target) {
    
                r = mid;
            } else if (nums[mid] < target) {
    
                l = mid + 1;
            }
            if(l >= r && l - 1 >= 0 && nums[l - 1] == target) {
    
                res[1] = l - 1;
            }
        }
        return res;
    }
}
原网站

版权声明
本文为[_ Cabbage_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230513032615.html