LeetCode-34.Find First and Last Position of Element in Sorted Array

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]

二分查找的变形 ,时间复杂度O(lgn)

    public int[] searchRange(int[] nums, int target) {//二分 my
        int[] re = new int[2];
        re[0] = bSearchFirst(nums,target);
        re[1] = bSearchLast(nums,target);
        return re;
    }
    
    private int bSearchFirst(int[] nums,int target){
        if(null==nums||0==nums.length){
            return -1;
        }
        int left = 0;
        int right = nums.length-1;
        while(left<= right){
            int mid = (left+right)/2;
            if(nums[mid] >target){
                right = mid-1;
            }
            else if(nums[mid]<target) {
                left = mid+1;
            }
            else if((mid==0)||(nums[mid-1]!=target)){//如果nums[mid]=target,而且是第一个
                    return mid;
            }
            else{//如果nums[mid]=target,而且不是第一个
                right = mid-1;
            } 
        }
        return -1;
    }
    private int bSearchLast(int[] nums,int target){
        if(null==nums||0==nums.length){
            return -1;
        }
        int left = 0;
        int right = nums.length-1;
        while(left<= right){
            int mid = (left+right)/2;
            if(nums[mid] >target){
                right = mid-1;
            }
            else if(nums[mid]<target){
                left = mid+1;
            }
            else if((mid==nums.length-1)||(nums[mid+1]!=target)){//如果nums[mid]=target,而且是最后一个
                    return mid;
            }
            else {//如果nums[mid]=target,而且是最后一个
                left = mid+1;
            }
        }
        return -1;
    }

 

posted @ 2019-06-14 14:57  月半榨菜  阅读(73)  评论(0编辑  收藏  举报