LeetCode Search for a Range
来源:互联网 发布:mac可以远程控制吗 编辑:程序博客网 时间:2024/06/03 18:18
Description:
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]
.
Solution:
Binary search.
We use a binary search to find the largest number that is smaller than target and the smallest number that is larger than target. Pay attention to the return number, especially the boundary condition.
public class Solution {public int[] searchRange(int[] nums, int target) {int maxSmaller = getMaxSmaller(nums, target);int minBigger = getMinBigger(nums, target);System.out.println(maxSmaller + " " + minBigger);return new int[] { maxSmaller, minBigger };}int getMaxSmaller(int[] nums, int target) {int l = 0, r = nums.length - 1, mid;while (l + 1 < r) {mid = (l + r) / 2;if (nums[mid] >= target)r = mid;elsel = mid;}if (nums[l] == target)return l;if (l < nums.length - 1 && nums[l + 1] == target)return l + 1;return -1;}int getMinBigger(int[] nums, int target) {int l = 0, r = nums.length - 1, mid;while (l + 1 < r) {mid = (l + r) / 2;if (nums[mid] <= target)l = mid;elser = mid;}if (nums[r] == target)return r;if (r > 0 && nums[r - 1] == target)return r - 1;return -1;}}
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
- php中查询mysql 如何在WHERE meta_id IN 中用数组
- GridView用CSS设定样式
- 通过分析 JDK 源代码研究 TreeMap 红黑树算法实现
- Cisco 中line密码的几点理解
- Execution failed for task ': :dexDebug'
- LeetCode Search for a Range
- android ant 多渠道打包
- 【Extjs】上传文件
- 进程、线程同步互斥学习 —— 信号量
- require.js的用法
- 计算机视觉(ComputerVision, CV)相关领域的网站链接
- Visual Studio查找高亮效果设置
- 《Linux内核设计与实现》读书笔记(十二)- 内存管理
- #笔记#圣思园 JavaWeb 第7讲——Servlet