lintcode:First Position of Target
来源:互联网 发布:中信手机炒股软件 编辑:程序博客网 时间:2024/06/16 16:34
For a given sorted array (ascending order) and a target
number, 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
.
Challenge
If the count of numbers is bigger than 2^32, can your code work properly?
Tags
Related Problems
class Solution {public: /** * @param nums: The integer array. * @param target: Target number to find. * @return: The first position of target. Position starts from 0. */ int binarySearch(vector<int> &array, int target) { // write your code here if (array.size() == 0) return -1; int left = 0; int right = array.size()-1; while (left <= right) { int mid = left+(right-left)/2; if (array[mid] == target) { if (mid > 0 && (array[mid-1] != target)) { return mid; } else if (mid == 0) { return 0; } else { right = mid-1; } } else if (array[mid] > target) { right = mid-1; } else { left = mid+1; } } return -1; }};
0 0
- lintcode:First Position of Target
- lintcode:First Position of Target
- [lintcode 14] First Position of Target
- first-position-of-target
- First Position of Target
- #14 First Position of Target
- last position of target / first position of target
- Binary Search---First Position of Target
- Lintcode14 First Position of Target Solution 题解
- 14.First Position of Target-二分查找(容易题)
- last-position-of-target
- Lintcode:First Position Unique Character
- lintcode(646)First Position Unique Character
- LintCode 744. Sum of first K even-length Palindrome numbers
- lintcode---Sum of first K even-length Palindrome numbers
- LintCode python 小白-简单题-646 First Position Unique Character
- [Lintcode] Search Insert Position
- [LeetCode] Search for a Range (sorted integers array,find start & end position of a target number)
- Papers about DL
- android 中HttpClient和URLConnection的区别
- Oracle查询语句
- 怎么设置viewpager在使用setCurrentItem的滑动速度
- dev gridview添加一button列
- lintcode:First Position of Target
- C++中const、volatile、mutable的用法
- 《Python核心编程》读书笔记(二)
- oracle表分区详解
- PTCHAR、LPSTR、LPCSTR、PSTR等的区别
- Android 实现串口的移植
- 复合类型之一 引用
- Java day09 String(1)
- Android Touch事件传递机制解析