LeetCode Search Insert Position
2014-06-07 12:28
337 查看
题目
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 begin=0,end=n-1,mid; while(begin<=end) { mid=(begin+end)/2; if(A[mid]==target) return mid; else if(A[mid]<target) begin=mid+1; else end=mid-1; } return begin; } };
相关文章推荐
- LeetCode - Search Insert Position
- leetcode Search Insert Position Python
- LeetCode-Search Insert Position
- leetcode 35. Search Insert Position
- 【LeetCode】Search Insert Position
- LeetCode(35) Search Insert Position
- leetcode35-search insert position
- [LeetCode 35] Search Insert Position Solution
- [LeetCode35]Search Insert Position
- LeetCode---35. Search Insert Position(查找插入位置)
- [leetcode 35] Search Insert Position
- LeetCode-35.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
- leetcode:Search Insert Position