LeetCode 34.Search for a Range

题目:

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].

思路:

1.当数组长度为0时,返回[-1,-1];

2.当数组长度为1时,判断nums[0]与target关系;

3.当数组长度大于1时:

(1)因题目要求时间复杂度O(log n),且整数数组以升序排列,故用二分法找出一个等于target的数组下标。

(2)起始坐标向前。

(3)结束坐标向后。

代码:

 1 public class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         int start = 0,end = nums.length-1,mid = 0;
 4         int resStart = -1,resEnd = -1;
 5         int[] resArr={-1,-1};
 6         if(nums.length == 0){
 7             resArr[0] = resArr[1] =-1;
 8             return resArr;
 9         }
10         if(nums.length == 1){
11             if(nums[0] == target){
12                 resArr[0] = resArr[1] =0;
13                 return resArr;
14             }else{
15                 resStart = resEnd =-1;
16                 return resArr;
17             }
18         }
19         while(start + 1 < end){
20             mid = start + (end - start)/2;
21             if(nums[mid] == target){
22                 resStart = resEnd = mid;
23                 break;
24             }else if(nums[mid] > target){
25                 end = mid;
26             }else{
27                 start = mid;
28             }
29         }
30         if(resStart == -1 && nums[start] == target){
31             resStart = resEnd = start;
32         }
33         if(resStart == -1 && nums[end] == target){
34             resStart = resEnd = end;
35         }
36         while(resStart >0){
37             if(nums[resStart-1] == target){
38                 resStart--;
39             }else{
40                 break;
41             }
42         }
43         while(resEnd < nums.length-1){
44             if(nums[resEnd+1] == target){
45                 resEnd++;
46             }else{
47                 break;
48             }
49         }
50         resArr[0] = resStart;
51         resArr[1] = resEnd;
52         return resArr;
53     }
54 }

 

posted @ 2017-03-31 17:19  程序媛家  阅读(180)  评论(0编辑  收藏  举报