Search Insert Position--寻找插入点Given a sorted array and a target value, return the index if the target
2014-06-22 17:26
330 查看
问题:链接
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) { if(A[0] >= target || n == 0) return 0; for(int i = 0; i < n; i++) { if(A[i] == target) return i; else if(i == n-1) return n; else if(A[i] < target && A[i+1] > target) { return i+1; } } } };
相关文章推荐
- Search Insert Position--寻找插入点Given a sorted array and a target value, return the index if the target
- Leetcode35:Search Insert Position寻找target元素(应)插入的位置
- The Solution to Leetcode 35 Search Insert Position
- 寻找序列的插入位置 Search Insert Position
- Search Insert Position 寻找插入的位置
- LeetCode-35:Search Insert Position(寻找或插入位置)
- [Leetcode] search insert position 寻找插入位置
- LeetCode Online Judge 题目C# 练习 - Search Insert Position
- The 'SelectedIndex' and 'SelectedValue' attributes are mutually exclusive.
- when jquery.ajax() call wcf,if success,how to use wcf return value?
- return the minimum value in a stack
- Assigning the return value of new by reference is deprecated in xxxx
- The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List
- About the return value of SetTimer function
- Insert 'value' into every element but the first
- ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the f
- java.lang.IllegalArgumentException: the bind value at index 1 is null
- 二叉查找树的一些操作(search,getminvalue,get maxvalue,insert)
- PHP显示Deprecated: Assigning the return value of new by reference is deprecated in解决办法
- set command will return the value of the argument( variable, actually )