Leetcode 34 Find First and Last Position of Element in Sorted Array

HowieLee59發表於2018-10-31

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]

這個題的意思是在一個陣列中尋找與target相等的兩個數並返回位置,要求時間複雜度為O(Log n),則可以看出使用二分法進行求,但是需要做一點變形,因為兩個數字相等的時候不適合二分。

1)

class Solution {
    public int[] searchRange(int[] nums, int target) {
            double left = target - 0.5, right = target + 0.5;
            int l = bs(nums, left), r = bs(nums, right);
            if(l == r) return new int[]{-1, -1};
            return new int[]{l, r-1};
    }
        
    public int bs(int[] nums, double target) {
            int l = 0, h = nums.length-1;
            while(l <= h){
                int m = l + (h - l)/2;
                if(target > nums[m]) l = m+1;
                else h = m-1;
            }
            return l;
    }
}

 

相關文章