1 #include "000库函数.h" 2 3 //第一眼,感觉没什么考虑算法的,就普通做就好了 4 //又因为是有序 的,故使用二分法最好了【别再太真爱用遍历,傻子才会一上来就遍历】 12ms 5 class Solution { 6 public: 7 int searchInsert(vector & nums, int target) { 8 if (nums.size() == 0 || target < nums[0])return 0;//为空或者是太小,则在首位插入 9 if (target > nums[nums.size() - 1])return nums.size();//太大在尾部插入10 int left = 0, right = nums.size() - 1;11 while (left < right) {12 int mid = left + (right - left) / 2;13 if (nums[mid] == target)return mid;14 if (nums[mid] < target) left = mid + 1;//使用这种判断,会找到最左边的目标值15 else right = mid;16 } 17 return right;18 }19 };20 21 void T035() {22 Solution s;23 vector nums = { 1,3,5,5,6 };24 cout << "*********************************" << endl;25 cout << s.searchInsert(nums, 4) << endl;26 cout << s.searchInsert(nums, 3) << endl;27 cout << s.searchInsert(nums, 5) << endl;28 cout << s.searchInsert(nums, 6) << endl;29 cout << s.searchInsert(nums, 7) << endl;30 31 }