Lintcode: First Position of Target (Binary Search)
2015-02-05 05:26
537 查看
Binary search is a famous question in algorithm. 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 MAXINT, can your code work properly?
跟Leetcode里search for a range挺像的,就是找到一个target之后,还要继续找它的左边沿。最后l指针超过r指针之后, l 指针会停在左边沿上
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) { int l = 0, r = nums.length - 1; int m = 0; while (l <= r) { m = (l + r) / 2; if (nums[m] == target) break; else if (nums[m] > target) r = m - 1; else l = m + 1; } if (nums[m] != target) return -1; l = 0; r = m; while (l <= r) { m = (l + r) / 2; if (nums[m] == target) { r = m - 1; } else l = m + 1; } return l; } }
相关文章推荐
- LintCode: First Position of Target
- lintcode:First Position of Target
- lintcode:First Position of Target
- Binary Search---First Position of Target
- Lintcode 14 first position of target
- #14 First Position of Target
- 【简单】Lintcode 14:First Position of Target
- last position of target / first position of target
- First Position of Target
- 二分查找(first-position-of-target)
- First Position of Target
- Lintcode14 First Position of Target Solution 题解
- [lintcode 14] First Position of Target
- [lintcode 14] First Position of Target
- [LintCode] 14 First Position of Target
- first-position-of-target
- 简单二分法-First Position of Target
- LintCode python 小白-简单题-646 First Position Unique Character
- lintcode-easy-First Position of Target
- LintCode 14. First Position of Target