Question:

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example:

  1. Input: [1,3,5,6], 5
  2. Output: 2
  3. Input: [1,3,5,6], 0
  4. Output: 0
  1. Input: [1,3,5,6], 2
  2. Output: 1
  3. Input: [1,3,5,6], 7
  4. Output: 4

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number}
  5. */
  6. var searchInsert = function(nums, target) {
  7. for (let i=0; i<nums.length; i++) {
  8. // 存在的情况
  9. if (nums[i] === target || nums[i]>target) {
  10. return i;
  11. break;
  12. }
  13. //比最后一个值还大
  14. if (i === nums.length-1) {
  15. return nums.length
  16. }
  17. }
  18. };

Runtime: 56 ms, faster than 39.87% of JavaScript online submissions for Search Insert Position.