题目直接截图于力扣(LeetCode)。算法
该题网址:https://leetcode-cn.com/problems/search-insert-position/spa
二分法、蛮力法code
蛮力法天然没必要多说,遍历就行。blog
有序队列是使用二分法的基础。使用二分法须要注意每次标动移动的边界,在左标兵右移时mid须要+1, 右标兵左移时mid须要-1。但貌似这道题中蛮力法和二分法执行速度差不了多少。队列
一、蛮力法leetcode
1 int searchInsert(int* nums, int numsSize, int target){ 2 int i; 3 for(i = 0; i < numsSize; i++) 4 { 5 if(nums[i] >= target) // ==是返回的底限,若是大于则表示以后没有等于,因此直接返回。 6 { 7 return i; 8 } 9 } 10 return i; 11 }
二、二分法get
int searchInsert(int* nums, int numsSize, int target){ int left=0, right=numsSize-1; int mid; while(left <= right) { mid = (left + right) / 2; if(nums[mid] == target) { return mid; } else if(nums[mid] < target) { left = mid+1; } else { right = mid-1; } } return left; }
2021-01-16 12:50:50it