1. 程式人生 > 實用技巧 >LeetCode第34題

LeetCode第34題

常規二分

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums == null || nums.length < 1){
            return new int[]{-1,-1};
        }
        int[] res = new int[]{-1,-1};
        int len = nums.length;
        int left = 0;
        int right = len - 1;
        
int mid = (left + right) >> 1;//尋找最小index時,不需要-1,因為右移會向下取整 while(left < right){//找leftIndex if(nums[mid] < target){ left = mid + 1; } else if(nums[mid] > target){ right = mid - 1; }else{ right
= mid; } mid = (left + right) >> 1; } if(nums[left] == target){ res[0] = left; } right = len - 1; mid = ((left + right) >> 1) + 1;//因為要尋找最大的index,而右移會向下取整,所以需要+1,不進行+1,會出現死迴圈的情況 while(left < right){//找rightIndex
if(nums[mid] < target){ left = mid + 1; } else if(nums[mid] > target){ right = mid - 1; }else{ left = mid; } mid = ((left + right) >> 1) + 1;//一定要+1,這是易錯點 } if(nums[right] == target){ res[1] = right; } return res; } }