First Position of Target
2016-07-04 01:22
417 查看
For a given sorted array (ascending order) and a
If the target number does not exist in the array, return
Example
If the array is
分析:
很明显的用binary search, 但是因为要找第一个,所以,我们需要判断一下。
参考请注明出处: cnblogs.com/beiyeqingteng/
targetnumber, find the first index of this number in
O(log n)time complexity.
If the target number does not exist in the array, return
-1.
Example
If the array is
[1, 2, 3, 3, 4, 5, 10], for given target
3, return
2.
分析:
很明显的用binary search, 但是因为要找第一个,所以,我们需要判断一下。
class Solution { /** * @param nums: The integer array. * @param target: Target to find. * @return: The first position of target. Position starts from 0. */ public int binarySearch(int[] nums, int target) { if (nums == null || nums.length == 0) return -1; int start = 0; int end = nums.length - 1; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { if (mid != 0 && nums[mid - 1] == target) { end = mid - 1; } else { return mid; } } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return -1; } }
参考请注明出处: cnblogs.com/beiyeqingteng/
相关文章推荐
- Linux下Nginx1.8安装
- NYOJ 猜猜我是第几个(康托展开)
- Google gflags库(解析命令行参数)
- <<从0到1 开启商业与未来的秘密>>读书笔记
- The concept of Homomorphic Encryption
- CSS居中之道
- 全球最杰出的14位程序员
- Win10 IoT C#开发 2 - 创建基于XAML的UI程序 及 应用的三种部署方法
- 浅谈C++类(6)--复制构造函数
- go语言实现斐波数列
- CNN for NLP
- 位操作
- leetcode题解日练--2016.7.3
- Chromium网页输入事件捕捉和手势检测过程分析
- iOS-FMDB
- iOS-使用CFStringTransform将汉字转换为拼音
- 工厂模式 详解
- RemObjects 客户端完整执行流程
- spring注解
- 合伙创业股权分配之实战模拟:分配股权都有哪些考量因素?