LeetCode 34. Search for a Range(搜索范围)
2016-05-20 10:36
453 查看
原题网址:https://leetcode.com/problems/search-for-a-range/
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
方法:二分法查找。
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[] nums, int target) { int[] range = new int[2]; range[0] = -1; range[1] = -1; int i=0, j=nums.length-1; while (i<=j) { int m = (i+j)/2; if (target == nums[m]) { range[0] = m; j = m-1; } else if (target < nums[m]) { j = m - 1; } else { i = m + 1; } } i=0; j=nums.length-1; while (i<=j) { int m = (i+j)/2; if (target == nums[m]) { range[1] = m; i = m + 1; } else if (target < nums[m]) { j = m - 1; } else { i = m + 1; } } return range; } }
相关文章推荐
- git命令详解(转)
- Murano Weekly Meeting 2016.05.10
- UD三分区补充教程1——激活不同分区对于UD三分区bios启动和uefi启动兼容性影响的讨论
- [python]时间操作
- IOS后台运行机制详解(一)
- MultipeerConnectivity 点对点连接
- 欢迎使用CSDN-markdown编辑器
- LeetCode 25. Reverse Nodes in k-Group(反转链表)
- LeetCode 26. Remove Duplicates from Sorted Array(删除重复)
- LeetCode 27. Remove Element(删除元素)
- LeetCode 29. Divide Two Integers(除法)
- LeetCode 28. Implement strStr()(实现子串定位)
- LeetCode 30. Substring with Concatenation of All Words(单词连接)
- linux 安装nginx
- (转)Kettle的数据同步
- JAXB - The JAXB Context
- cc1110mdk烧写
- 2015年08月01日——如何无损制作UD三分区的双启U盘(20150801图文),已经编程实现!
- zabbix初探之安装
- USB详解(转)