题目描述: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
- 顺序查找:时间复杂度O(n)
//C int searchInsert(int* nums, int numsSize, int target){ int i; for(i = 0; i < numsSize; i++){ if(nums[i] >= target) return i; } return i; } //JS var searchInsert = function(nums, target) { var i = 0, len = nums.length; for(; i < len; i++) { if(nums[i] >= target) return i; } return i; };
- 折半查找:时间复杂度O(logn)
//C int searchInsert(int* nums, int numsSize, int target){ int low = 0, high = numsSize - 1, mid; while(low <= high){ mid = (low + high) / 2; if(nums[mid] == target) return mid; else if(nums[mid] > target) high = mid - 1; else low = mid + 1; } return low; } //JS var searchInsert = function(nums, target) { let low = 0, high = nums.length - 1, mid = 0; while(low <= high){ mid = Math.floor((low + high) / 2); if(nums[mid] == target) return mid; else if(nums[mid] > target) high = mid - 1; else low = mid + 1; } return low; };