[LeetCode] 35. Search Insert Position (JavaScript)

nemo·2022년 5월 12일
0

문제

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

target이 배열에 있다면 해당 인덱스를 출력하고, 없다면 target의 자리를 찾아 인덱스를 출력한다.

입력 예제

nums = [1,3,5,6], target = 7

출력 예제

4




풀이

var searchInsert = function(nums, target) {  
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === target || nums[i] > target) return i;
    else if (nums[nums.length - 1] < target) return nums.length;
  }
};

0개의 댓글