天天看点

LeetCode 34. Search for a Range(搜索范围)

原题网址:https://leetcode.com/problems/search-for-a-range/

Given a sorted array of integers, 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]

.

For example,

Given 

[5, 7, 7, 8, 8, 10]

 and target value 8,

return 

[3, 4]

.

方法:二分法查找。

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] range = new int[2];
        range[0] = -1;
        range[1] = -1;
        int i=0, j=nums.length-1;
        while (i<=j) {
            int m = (i+j)/2;
            if (target == nums[m]) {
                range[0] = m;
                j = m-1;
            } else if (target < nums[m]) {
                j = m - 1;
            } else {
                i = m + 1;
            }
        }
        i=0;
        j=nums.length-1;
        while (i<=j) {
            int m = (i+j)/2;
            if (target == nums[m]) {
                range[1] = m;
                i = m + 1;
            } else if (target < nums[m]) {
                j = m - 1;
            } else {
                i = m + 1;
            }
        }
        return range;
    }
}