LeetCode Search Insert Position
2015-01-29 20:48
260 查看
Search Insert Position
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.
思路:折半查找。
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.
[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) { int i = 0, j = n - 1, m = (i + j) / 2; while(i <= j) { if(target == A[m]) return m; else if(i == j) break; else if(target < A[m]) j = m - 1; else i = m + 1; m = (i + j) / 2; } if(i == n - 1 && target > A[i]) return n; else if(A[i] < target && A[i + 1] > target) return i + 1; else return i; } };
思路:折半查找。
相关文章推荐
- 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-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】C# 35、Search Insert Position
- [LeetCode][Java] Search Insert Position
- LeetCode 35. Search Insert Position(查找插入位置)