程序媛詹妮弗
终身学习

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]

 

题意:

给定一个有序数组,找出某个值的起始和终止区间。

 

思路:

二分查找

 

代码:

 1 class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         // corner case
 4         if(nums == null || nums.length == 0) return new int[]{-1,-1};
 5         int left = findFirst(nums, 0, nums.length-1, target);
 6         if(left == -1) return new int[]{-1,-1};
 7         int right = findLast(nums, 0, nums.length-1, target);
 8         return new int[]{left, right};
 9 
10     }
11     // find start point
12     private int findFirst(int[] nums, int left, int right, int target) {
13         // avoid dead looping
14         while(left + 1 < right){
15             // avoid overflow
16             int mid =  left + (right - left)/2;
17             //   left------ |mid| ---target---right 
18             if(nums[mid] < target){
19                 left = mid;
20             }
21             //   left---target---|mid| ------right 
22             else{
23                 right = mid;
24             }
25         }
26         if (nums[left] == target) return left;
27         if (nums[right] == target) return right;
28         return -1;
29     }
30 
31     private int findLast(int[] nums, int left, int right, int target) {
32         while(left + 1 < right){
33             int mid =  left + (right - left)/2;
34              //   left---target---|mid| ------right 
35             if(nums[mid] > target){
36                 right = mid;
37             }
38             //   left------ |mid| ---target---right 
39             else{
40                 left = mid;
41             }
42         }
43         if(nums[right] == target) return right;
44         if (nums[left] == target) return left;
45         return -1;
46     }
47 }

 

posted on 2018-06-05 08:23  程序媛詹妮弗  阅读(141)  评论(0编辑  收藏  举报