[LeetCode]Search for a Range
来源:互联网 发布:丝绸之路发展历程 知乎 编辑:程序博客网 时间:2024/05/21 07:50
Description:
Given an array of integers sorted in ascending order, 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].
题意理解: 其实这道题求target的起点和终点,并且要求时间复杂度为O(logn),所以可以通过用二分法来找到target的边界值。
code:
public int[] searchRange(int[] nums, int target) { int[] result = new int[2]; result[0] = findFirst(nums, target); result[1] = findLast(nums, target); return result;}private int findFirst(int[] nums, int target){ int idx = -1; int start = 0; int end = nums.length - 1; while(start <= end){ int mid = (start + end) / 2; if(nums[mid] >= target){ end = mid - 1; }else{ start = mid + 1; } if(nums[mid] == target) idx = mid; } return idx;}private int findLast(int[] nums, int target){ int idx = -1; int start = 0; int end = nums.length - 1; while(start <= end){ int mid = (start + end) / 2; if(nums[mid] <= target){ start = mid + 1; }else{ end = mid - 1; } if(nums[mid] == target) idx = mid; } return idx; }
阅读全文
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
- MyBatis环境搭建入门
- 详谈java内存模型
- MySQL相关的建表语句
- Java多线程——<七>多线程的异常捕捉
- java基础——重载
- [LeetCode]Search for a Range
- .net平台常用框架
- String 类是不可改变的解析
- 对自己的规划
- 数据倾斜解决方案之六:使用随机数进行Join
- serevlt特点
- jsp
- Java StringBuffer 和 StringBuilder 类
- [Thinking in java]理解java三大特性之一继承