Search for a Range
2015-03-07 09:56
113 查看
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
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].
public class Solution { public int[] searchRange(int[] A, int target) { // Start typing your Java solution below // DO NOT write main() function int[] res = new int[2]; res[0] = lowerbound(A,target); res[1] = upperbound(A,target); return res; } public static int upperbound(int[] num, int target){ //find last 2, int low=0; int high=num.length - 1; int mid = low + (high-low+1)/2; while(low<high){ mid = low + (high-low+1)/2; if(num[mid]<=target){ low = mid; } else { high = mid - 1; } } return num[low] == target ? low : -1; } public static int lowerbound(int[] num, int target){ //find first 2. int low=0; int high=num.length - 1; int mid = low + (high-low)/2; while(low<high) { mid = low + (high-low)/2; if(num[mid]>=target){ high = mid; } else { low = mid + 1; } } return num[high] == target ? high : -1; } }
相关文章推荐
- Search for a Range
- [LeetCode] Search for a Range 二分搜索
- Search for a Range leetcode java
- 【leetcode】Search for a Range
- LeetCode c语言-Search for a Range
- LeetCode | Search for a Range
- LeetCode OJ-34.Search for a Range
- LeetCode #34 - Search for a Range
- Leetcode之Search for a Range
- 二分查找之Search for a Range
- leetcode 34. Search for a Range
- [Leetcode] #34 Search for a Range
- Leetcode126: Search for a Range
- Search for a Range
- LeetCode(034) Search For a Range (Java)
- Search for a Range
- (java) Search for a Range
- LeetCode- Search for a Range - Python
- #61 Search for a Range
- 74-Search for a Range