码迷,mamicode.com
首页 > 其他好文 > 详细

Search for a Range 解答

时间:2015-10-19 08:13:25      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

Question

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

Solution

Use binary search, first, find left position, then, find right position.

 1 public class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         int[] result = new int[2];
 4         result[0] = -1;
 5         result[1] = -1;
 6         if (nums == null || nums.length < 1)
 7             return result;
 8         int start = 0, end = nums.length - 1, mid, first, last;
 9         // Find first position of target
10         while (start + 1 < end) {
11             mid = (end - start) / 2 + start;
12             if (nums[mid] >= target)
13                 end = mid;
14             else
15                 start = mid;
16         }
17         if (nums[start] == target)
18             result[0] = start;
19         else if (nums[end] == target)
20             result[0] = end;
21         
22         // Find last position of target
23         start = 0;
24         end = nums.length - 1;
25         while (start + 1 < end) {
26             mid = (end - start) / 2 + start;
27             if (nums[mid] <= target)
28                 start = mid;
29             else
30                 end = mid;
31         }
32         if (nums[end] == target)
33             result[1] = end;
34         else if (nums[start] == target)
35             result[1] = start;
36         return result;
37     }
38 }

 

Search for a Range 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4890857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!