[Binary Search] 34. Find the first and last position of an element in a sorted array

34. Find the first and last position of an element in a sorted array

problem solving ideas

insert image description here

  • use binary search
  • After finding the index of the target element
  • Then look for the target element left and right, then record the interval position and save it
class Solution {
    
    
    public int[] searchRange(int[] nums, int target) {
    
    
        // 使用二分查找  数组有序
        int left = 0;
        int right = nums.length  - 1;
        int[] result = new int[2];
        while(left <= right){
    
    
            int mid = left + (right - left) / 2;
            if(nums[mid] > target){
    
    
                right = mid  -1;
            }else if(nums[mid] < target){
    
    
                left = mid + 1;
            }else{
    
    
                // 找到目标元素之后
                // 寻找mid左右的区间
                int i = mid;
                int j = mid;

                // 寻找右边区间
                while(j <= nums.length - 1 && nums[j] == target){
    
    
                    j++;
                }

                while(i >= 0 && nums[i] == target){
    
    
                    i--;
                }

                result[0] = ++i;
                result[1] = --j;

                return result;
            }
        }

        result[0] = -1;
        result[1] = -1;

        return result;

        
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131626868