Search for a Range
来源:互联网 发布:oracle连接mysql详解 编辑:程序博客网 时间:2024/06/04 23:19
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]
.
Have you met this question in a real interview?
思路 : 肯定是 binary search .最后再向两边扩展。
public class Solution { public int[] searchRange(int[] A, int target) { int[] ret = new int[2]; ret[0] = -1; ret[1] = -1; if(A.length < 1) return ret; int left = 0; int right = A.length - 1; boolean isFind = false; while(left <= right){ int mid = (left + right) / 2; if(A[mid] == target){ left = mid; right = mid; while(left >= 0 && A[left] == target) left--; while(right < A.length && A[right] == target) right++; ret[0] = left + 1; ret[1] = right - 1; return ret; }else if(A[mid] < target) left = mid + 1; else right =mid - 1; } return ret; }}
0 0
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range !!!
- Search for a Range
- Search for a Range
- Search For A Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Search for a Range
- Duplicate Emails Leetcode SQL
- Triangle Leetcode Python
- dedecms导航,当前栏目高亮显示代码
- linux ulimit调优
- Hadoop 使用 MapReduce 排序 思路、全局排序
- Search for a Range
- java输出二进制,八进制,十六进制数
- 124. Binary Tree Maximum Path Sum Leetcode Python
- 4Sum
- Valid Palindrome Leetcode Python
- LeetCode(127) Word Ladder
- Longest Consecutive Sequence Leetcode Python
- Integer.parseInt(s, radix)
- 位运算