Leetcode-Search for a range
2014-11-21 05:06
218 查看
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
For example,
Given
return
Have you met this question in a real interview?
Analysis:
We need to do two binary search. The first finds out the left boundary and the second finds out the right boundary.
if mid==target, we then check whether mid-1==target, if yes, we then continue to search [start,mid-1] until we find the left boundary.
Solution:
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].
Have you met this question in a real interview?
Analysis:
We need to do two binary search. The first finds out the left boundary and the second finds out the right boundary.
if mid==target, we then check whether mid-1==target, if yes, we then continue to search [start,mid-1] until we find the left boundary.
Solution:
public class Solution { public int[] searchRange(int[] A, int target) { int[] res = new int[]{-1,-1}; if (A.length==0) return res; int start = 0, end = A.length-1; //Find left range. while (start<=end){ int mid = (start+end)/2; if (A[mid]==target){ //find right range also. if (mid+1==A.length || A[mid+1]!=target) res[1] = mid; //Check left if (mid-1==-1 || A[mid-1]!=target){ res[0]=mid; break; } else { end = mid-1; continue; } } else if (A[mid]>target) end = mid-1; else start = mid+1; } if (start>end) return res; if (res[0]!=-1 && res[1]!=-1) return res; //Find right start = 0; end = A.length-1; while (start<=end){ int mid = (start+end)/2; if (A[mid]==target){ //Check right if (mid+1==A.length || A[mid+1]!=target){ res[1]=mid; break; } else { start = mid+1; continue; } } else if (A[mid]>target) end = mid-1; else start = mid+1; } return res; } }
相关文章推荐
- leetcode -- Search for a Range (TODO)
- LeetCode Search for a Range
- LeetCode —— Search for a Range
- LeetCode | Search for a Range
- leetcode: Search for a Range
- LeetCode: Search for a Range
- [Leetcode 89] 34 Search for a Range
- LeetCode 38: Search for a Range
- Leetcode Search for a Range
- [LeetCode]Search for a Range
- [Leetcode] Search for a Range
- [LeetCode] Search for a Range
- [LeetCode] Search for a Range 解题报告
- LeetCode: Search for a Range
- leetcode 96: Search for a Range
- [LeetCode] Search for a Range
- [leetcode] Search for a Range
- [Leetcode] Search for a Range
- Leetcode: Search for a Range
- LeetCode - Search for a Range