1. 程式人生 > 實用技巧 >LeetCode34. 在排序陣列中查詢元素的第一個和最後一個位置

LeetCode34. 在排序陣列中查詢元素的第一個和最後一個位置

LeetCode34. 在排序陣列中查詢元素的第一個和最後一個位置

  1. 題目跳轉
  2. 二分邊界問題參考
  3. JAVA程式碼:
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums.length == 0) return new int[]{-1, -1};
        int[] res = new int[2];
        res[0] = binarySearchFirst(nums, target, 0, nums.length);        
        res[1] = res[0] == -1? -1 : binarySearchSecond(nums, target, 0, nums.length);
        return res;
    }
	
    //查詢左邊界
    public int binarySearchFirst(int[] nums, int target, int left, int right){
        while(left < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] >= target){
                right = mid;
            }else if(nums[mid] < target){
                left = mid + 1;
            }
        }
        if (left == nums.length) return -1;
        return nums[left] == target ? left : -1;
    }
	
    //查詢右邊界
    public int binarySearchSecond(int[] nums, int target, int left, int right){
        while(left < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] > target){
                right = mid;
            }else if(nums[mid] <= target){
                left = mid + 1;
            }
        }
        if (left == 0) return -1;
        return nums[left - 1] == target ? (left - 1) : -1;
    }
}