【LeetCode】Search Insert Position
2014-03-12 20:36
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.
class Solution {
public:
int searchInsert(int A[], int n, int target)
{
if(target < A[0])
return 0;
if(target > A[n-1])
return n;
for(int i = 0; i < n; i++)
{
if(A[i] == target)
return i;
if(target > A[i] && target < A[i+1])
return i+1;
}
}
};
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)
{
if(target < A[0])
return 0;
if(target > A[n-1])
return n;
for(int i = 0; i < n; i++)
{
if(A[i] == target)
return i;
if(target > A[i] && target < A[i+1])
return i+1;
}
}
};
相关文章推荐
- leetcode Search Insert Position
- 【题解】【数组】【查找】【Leetcode】Search Insert Position
- LeetCode:Search Insert Position
- leetcode第一刷_Search Insert Position
- LeetCode 35 — Search Insert Position(C++ Java Python)
- LeetCode-35. Search Insert Position
- LeetCode(34)SearchInsertPosition
- Leetcode 35. Search Insert Position (Medium) (java)
- leetcode[35]:Search Insert Position
- Leetcode-search-insert-position
- [leetcode Search Insert Position]week 17
- Leetcode(35) Search Insert Position
- LeetCode题解:Search Insert Position
- LeetCode 035 Search Insert Position
- leetcode:Search Insert Position 【Java 】
- LeetCode 35. Search Insert Position
- leetcode-- 35. Search Insert Position
- leetcode解题之35#Search Insert Position Java版 递归和非递归实现
- LeetCode 35. Search Insert Position(查找插入位置)
- LeetCode Online Judge 题目C# 练习 - Search Insert Position