LeetCode- Find First and Last Position of Element in Sorted Array (JAVA)

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]

在有序數組中查找數字出現的首末位置

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int[] ret = new int[]{-1, -1};
        if(right < 0) {
            return ret;
        }
        
        int mid = right / 2;
        while(nums[mid] != target) {
            if(nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
            if(left > right) {
                return ret;
            }
            int temp = (right - left) / 2;
            mid = left + temp;
        }
        left = mid - 1;
        right = mid + 1;
        while(left >= 0 && nums[left] == target) {
            left--;
        }
        ret[0] = left + 1;
        while(right <nums.length && nums[right] == target) {
            right++;
        }
        ret[1] = right - 1;
        return ret;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章