Question:
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
思路:
给定有序数组,如果target在数组中,返回索引标号,如果不在,则将target插入数组并返回索引。
依次循环比较就好了,二分法可能会更快一点,懒所以没写。
Code:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.empty()){
nums.push_back(target);
return 0;
}
int x = 0;
for(int i = 0 ;i < nums.size(); i++ ){
if(nums[i]>=target){
x = i;
break;
}
if(i==nums.size()-1 && nums[i]<target){
x = i+1;
break;
}
}
return x;
}
};