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]


class Solution {
    public int[] searchRange(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        if (nums.length == 0) return new int[]{-1, -1};
        while (l < r) {
            int mid = (l + r) >> 1;
            if (nums[mid] >= target) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        
        int []ans = new int[2];
        if (nums[l] == target)
            ans[0] = l;
        else 
            ans[0] = -1;
        
        System.out.println(ans[0]);
        l = 0;
        r = nums.length - 1;
        while (l < r) {
            int mid = (l + r) >> 1;
            if (nums[mid] <= target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        if (r < nums.length && r >= 0 && nums[r] == target) {
            ans[1] = r;
        } else if (r - 1 >= 0 && nums[r - 1] == target) {
            ans[1] = r - 1;
        } else
            ans[1] = -1;
        
        return ans;
    }
}

 

posted @ 2020-02-14 23:12  hyx1  阅读(87)  评论(0编辑  收藏  举报