[Leetcode] Search Insert Position
2014-11-16 21:21
239 查看
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.
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
class Solution { public: int searchInsert(int A[], int n, int target) { return binaryInsert(A,0,n-1,target); } int binaryInsert(int A[],int low,int high,int target) { if(low == high) { if (A[low] >= target) return low; else return low+1; } int mid = (low + high) / 2; if (A[mid] == target) return mid; else if (A[mid] > target) return binaryInsert(A,low,mid,target); else return binaryInsert(A,mid+1,high,target); } };
相关文章推荐
- LeetCode:Search Insert Position
- 【leetcode】Array——Search Insert Position(35)
- [LeetCode][Java] Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode - Search Insert Position
- LeetCode Search Insert Position
- Leetcode_Search Insert Position
- 【LeetCode】Search Insert Position
- leetcode-35 Search Insert Position
- LeetCode: Search Insert Position
- *LeetCode Search Insert Position -- lower_bound
- 【leetcode】Search Insert Position
- [LeetCode 35] Search Insert Position Solution
- leetcode(35) - Search Insert Position
- [Leetcode]Search Insert Position
- LeetCode - 35. Search Insert Position
- [LeetCode] Search Insert Position
- leetcode — search-insert-position
- [LeetCode] Search Insert Position
- 【LeetCode】C# 35、Search Insert Position