[LeetCode] 34. Search for a Range

</br>


Given an array of integers 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].

For example,

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].


</br>

Solution

The target is to achieve this algorithm with the runtime complexity of O(log n), therefore we cannot implement regular search method or even achieving this in one pass. The complexity of O(log n) immediately reminds us of Quick Sort. We can compare the middle value of the the array with the target and find out the exact spot of the target.
</br>
Hence, we can implement Binary Search.

First, find the left boundary of the range. We initialize the range to [i=0, j=n-1]. In each step, calculate the middle element [mid = (i+j)/2]. Now according to the relative value of A[mid] to target, there are three possibilities:
[1] If A[mid] < target, then the range must begins on the right of mid (hence i = mid+1 for the next iteration)
[2] If A[mid] >= target, it means the range must begins on the left of mid (j = mid)
</br>
However, how can we make sure that the return value of this search is the very first one in this array.

Suppose our target is 5, let's take a look at these scenarios.

case 1: [5 7] (A[i] = target < A[j])
case 2: [5 5] (A[i] = target = A[j])
case 3: [3 5] (A[j] = target > A[i])
case 4: [3 7] (A[i] < target < A[j])
case 5: [6 7] (target < A[i] < A[j])

For case 1, and 2, if we follow the above rule, since mid = i => A[mid] = target in these cases, then we would set j = mid. Now the loop terminates and i and j both point to the first 5.
For case 3, since A[mid] < target, then set i = mid+1. The loop terminates and both i and j point to 5.
For all other cases, by the time the loop terminates, A[i] is not equal to 5. So we can easily know 5 is not in the sequence if the comparison fails.

In conclusion, when the loop terminates, the algorithm can always return the index of the number that is bigger or equals the target; otherwise, just return -1.
</br>
And for the last index of the target, we can inverse the implement of the Binary Search and start from the back of the array. Or we can actually search for the first index of the first number that is bigger than the target, and the index-1 is the last index of the target.

For [5, 7, 7, 8, 8, 10], we can do binary search for 9, and the binary search will return the index of the first number that is larger or equals 9, which is the last index of target plus one.
</br>

The code is shown as below.
Java

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        
        int start = binarySearch(nums,target);
        int end = binarySearch(nums,target+1)-1;
        
        if(start == nums.length || nums[start] != target)
            return new int[]{-1,-1};
        else
            return new int[]{start,end};
    }
    
    private static int binarySearch(int[] nums, int target) {
        
        int low = 0, high = nums.length;
        
        while (low < high) {
            int mid = low + ((high - low) >> 1);

            if (nums[mid] < target) 
                low = mid + 1;
            else 
                high = mid;
        }
        return low;
    }
}

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,083评论 0 23
  • 感恩父母养育之恩愿母亲身体健康衣食无忧智慧增长!感恩母亲教会我要有耐心爱心细心!感恩母亲给我机会种下财富种子健康种...
    T上善若水阅读 171评论 0 0
  • 清晨五点起床、晚上十点之前就寝,这样一种简素而规则的生活宣告开始。一日之中,身体机能最为活跃的时间因人而异,在我是...
    冉景雨阅读 273评论 1 1
  • 金丝皇菊的功效与作用金丝皇菊,来自江西修水,修水自然资源丰富,是贡茶宁红的故乡。金丝皇菊是当地一宝,人工除草,施农...
    阳光下的_b325阅读 1,645评论 0 0
  • 地铁偶遇一位青年歌手,述说自己的经历,他谈到了他的梦想,坚持唱歌。在拥挤的人群里,他显得那么突兀,人们的冷眼旁观,...
    穿越的艾伦阅读 216评论 0 0