LeetCode: Search Insert Position
2012-10-08 12:17
295 查看
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
5 → 2
2 → 1
7 → 4
0 → 0
标准的二分搜索算法,在结束的时候,如果没有找到target:那么r指向小于target的最大的数,l指向大于target的最小的数。
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6],
5 → 2
[1,3,5,6],
2 → 1
[1,3,5,6],
7 → 4
[1,3,5,6],
0 → 0
标准的二分搜索算法,在结束的时候,如果没有找到target:那么r指向小于target的最大的数,l指向大于target的最小的数。
class Solution { public: int binarySearch(int A[], int n, int target) { int l = 0; int u = n - 1; int p = -1; while (l <= u) { int mid = l + (u-l)/2; if (A[mid] == target) { p = mid; break; } else if (A[mid] < target) { l = mid + 1; } else u = mid - 1; } return p == -1 ? l : p; } int searchInsert(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function if (n == 0) return 0; return binarySearch(A, n, target); } };
相关文章推荐
- LeetCode--Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode-35-Search Insert Position
- [leetcode-34]Search Insert Position(c)
- Leetcode: Search Insert Position
- [LeetCode]题解(python):035-Search Insert Position
- leetcode-35-Search Insert Position
- [LeetCodeSearch Insert Position
- leetcode:Search Insert Position
- Search Insert Position——LeetCode
- [leetcode]35. Search Insert Position
- [LeetCode]Search Insert Position
- leetcode Search Insert Position
- 【LeetCode】35. Search Insert Position
- [leetcode] 35. Search Insert Position
- leetcode 35 Search Insert Position(二分法)
- leetcode解题方案--035--Search Insert Position
- 弱渣leetcode刷题-Search Insert Position
- [LeetCode] 035. Search Insert Position (Medium) (C++)
- LeetCode 035: Search Insert Position