本文共 549 字,大约阅读时间需要 1 分钟。
题目:
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(vector & nums, int target) { for (unsigned int i = 0; inums[i] && i == nums.size() - 1){//如果刚好在末尾 return i + 1; } } }};
转载地址:http://wnmii.baihongyu.com/