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

题目:

给定按升序排列的整数数组,找到给定目标值的起始和终止位置。

您的算法的运行时复杂度必须是O(log n的顺序

如果在数组中找不到目标,返回[-1, -1]

例如,
给定[5, 7, 7, 8, 8, 10]和目标值8,
返回[3, 4]

 

思路:

(1)首先在数组中找到target第一次出现位置的下标start

(2)若若数组中不存在target则返回new int[]{-1,-1}

(3)否则返回在数组中找到target的结束位置end

(4)最后返回new int[]{start,--end};

 

代码:

 1 class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         
 4         //寻找target在nums中起始位置下标
 5         int start=0;
 6         
 7         for(;start<nums.length;start++){
 8             
 9             if(nums[start]==target){
10                 
11                 break;
12                 
13             }
14             
15         }
16         
17         //若数组中没有target则返回[-1,-1];
18         if(nums.length==start){
19             
20             return new int[]{-1,-1};
21             
22         }
23         
24         //在数组nums中寻找target的结束位置下标
25         int end=start;
26         for(;end<nums.length;end++){
27             
28             if(nums[end]!=target){
29                 
30                 break;
31                 
32             }
33             
34         }
35         
36         return new int[]{start,--end};
37         
38         
39     }
40 }

 

posted @ 2017-10-19 22:02  xzy不会飞的地板流  阅读(212)  评论(0编辑  收藏  举报