leetcode:Search for a Range
来源:互联网 发布:百度世界大会 知乎 编辑:程序博客网 时间:2024/05/18 23:54
二分搜索算法的进化版:
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 { private int binarySearch(int[] A, int target) { if(A.length == 0) return -1; int right = A.length - 1; int left = 0; while(left<=right) { int middle = left + (right-left)/2; if(target > A[middle]) left = middle + 1; else if(target < A[middle]) right = middle - 1; else return middle; } return -1; } private int leftMost(int[] A, int left, int right, int target){ while(left <= right) { int middle = left + (right - left)/2; if(target == A[middle]) { if(middle != 0 && A[middle] == A[middle - 1]) right = middle - 1; else { return middle; } } else { left = middle + 1; } } return -1; } private int rightMost(int[] A, int left, int right, int target) { while(left <= right) { int middle = left + (right - left)/2; if(target == A[middle]){ if(middle != (A.length - 1) && A[middle] == A[middle + 1]) left = middle + 1; else { return middle; } } else { right = middle - 1; } } return -1; } public int[] searchRange(int[] A, int target) { int anchor = binarySearch(A, target); int left = -1; int right = -1; if(anchor != -1) { left = anchor; right = anchor; if(anchor != 0 && A[anchor] == A[anchor -1]) { //lets find the left most index left = leftMost(A, 0, anchor - 1, target); } if(anchor != (A.length-1) && A[anchor] == A[anchor+1]) { //lets find the right most index right = rightMost(A, anchor + 1, A.length - 1, target); } } return new int[] {left, right}; }}
0 0
- 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 Search for a Range
- [LeetCode]Search for a Range
- LeetCode-Search for a Range
- [leetcode] Search for a Range
- LeetCode - Search for a Range
- Search for a Range leetcode
- 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
- Facebook如何编程:扎克伯格亲自把关代码更新
- JavaScript权威指南_46_第6章_对象_6.9-序列化对象
- 增加根分区大小(root分区大小不够用了)
- android 相册实时更新
- Junit中对私有方法测试
- leetcode:Search for a Range
- DedeCMS借助function扩展实现特殊调用
- No result defined for action and result input
- iOS开发 UIWebView获取点击图片
- sqllite 之根据时间区间筛选数据
- IE8报错:Unable to modify the parent container element before the child element is closed
- Criteria Query常用的查询限制方法
- JavaScript权威指南_47_第6章_对象_6.10-对象方法
- python快速学习笔记