34 Find First and Last Position of Element in Sorted Array


自己写的, accepted 

class Solution {
    public int[] searchRange(int[] nums, int target) {
        // sanity check 
        if(nums == null || nums.length == 0) return new int[]{-1, -1};
        int[] res = new int[2];
        res[0] = first(nums, target);
        res[1] = last(nums, target);
        return res;
    }
    private int first(int[] nums, int target){
        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] == target){
                right = mid;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        if(nums[left] != target) return -1;
        return left;
    }
    
    private int last(int[] nums, int target){
        int left = 0;
        int right = nums.length - 1;
        while(left < right - 1){
            int mid = left + (right - left) / 2;
            if(nums[mid] == target){
                left = mid;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else{
                right = mid;
            }
        }
        // post processing 
        if(nums[right] == target) return right;
        if(nums[left] == target) return left;
        return -1;
    }
}

 这个也是, 得自己走例子, 才知道什么时候需要post processing , 什么时候不需要, 这个题一个问不需要, 第二问就需要了

所以不要背答案, 要真的理解, 自己走例子


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]

posted on 2018-08-10 14:47  猪猪&#128055;  阅读(556)  评论(0)    收藏  举报

导航