leetcode -35
法一:二分法
class Solution { public: int searchInsert(vector<int>& nums, int target) { if(target<nums[0])return 0; if(target>nums[nums.size()-1])return nums.size(); int left=0,right=nums.size()-1; while(left<right){ int center=left+(right-left)/2; if(target==nums[center])return center; else if(target>nums[center])left=center+1; else right=center; } return right; } };
法2:遍历
class Solution { public: int searchInsert(vector<int>& nums, int target) { for(int i=0;i<nums.size();i++){//找出比target大或等于的数就好了 if(nums[i]>=target)return i; } return nums.size(); } };