leetcode 96: Search for a Range
2013-03-03 18:07
441 查看
Search for a RangeMar
3 '12
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
3 '12
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].
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; } }
相关文章推荐
- leetcode 96: Search for a Range
- LeetCode-Search for a Range
- [Leetcode]_34 Search for a Range
- LeetCode——Search for a Range
- LeetCode 34.Search for a Range
- Leetcode: Search for a Range
- LeetCode力扣之Search for a Range
- [LeetCode]34. Search for a Range
- leetcode(34) - Search for a Range
- Leetcode Search for a Range
- LeetCode | Search for a Range
- LeetCode 34 Search for a Range (有序数组中查找给定数字的起止下标)
- leetcode--Search for a Range
- leetcode-34. Search for a Range
- Leetcode 34. Search for a Range
- 小白笔记--------------------------leetcode 34. Search for a Range
- 【LeetCode】Search for a Range
- leetcode -- Search for a Range -- 思路简单,要再做一遍
- (leetcode)Search for a Range
- LeetCode(034) Search For a Range (Java)