class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i = 0;
for (; i < nums.size(); ++i) {
if (nums[i] == target) return i;
else if (nums[i] > target) return i;
}
return i;
}
};
二分法
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0, mid = 0;
int high = nums.size();
while(low < high) {
mid = low + (high - low) / 2;
if(nums[mid] > target) {
high = mid;
}
else if(nums[mid] < target) {
low = mid + 1;
}
else return mid;
}
return low;
}
};