暴力解法:
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
for (int i = 0; i < len;i++) {
if (nums[i] >= target) {
return i;
}
}
return len;
}
效果出乎意料的不错
二分法:
(不太标准)
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
int i = 0, j = len - 1;
if (nums[0] > target)
return 0;
if (nums[len - 1] < target)
return len;
while (nums[i]<target && nums[j]>target && (i + 1) != j) {
if (nums[(i + j) / 2] > target) {
j = (i + j) / 2;
}
else if (nums[(i + j) / 2] < target) {
i = (i + j) / 2;
}
else {
return (i + j) / 2;
}
}
if (nums[i] == target) {
return i;
}
return j;
}
(标准点的)
int searchInsert(vector<int>& nums, int target) {
int i = 0, j = nums.size() - 1;
if (nums[j] < target) {
return nums.size();
}
int mid;
while (i < j) {
mid = (i + j) / 2;
if (nums[mid] < target) {
i = mid + 1;
}
else {
j = mid;
}
}
return i;//返回时必有i=j
}