728x90
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.
Example 1:
nput: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints:
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums contains distinct values sorted in ascending order.
- -10^4 <= target <= 10^4
Solutions Code :
var searchInsert = function(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] === target) {
return mid; // target을 찾은 경우 해당 인덱스 반환
} else if (nums[mid] < target) {
left = mid + 1; // 중간 값보다 큰 경우 오른쪽 부분 탐색
} else {
right = mid - 1; // 중간 값보다 작은 경우 왼쪽 부분 탐색
}
}
// while 루프를 빠져나왔을 때 left가 삽입 위치가 됨
return left;
};
출처 : https://leetcode.com/problemset/all/
728x90
'LeetCode' 카테고리의 다른 글
[LeetCode] 37. Sudoku Solver (0) | 2023.11.02 |
---|---|
[LeetCode] 36. Valid Sudoku (0) | 2023.11.02 |
[LeetCode] 34. Find First and Last Position of Element in Sorted Array (2) | 2023.10.31 |
[LeetCode] 33. Search in Rotated Sorted Array (2) | 2023.10.31 |
[LeetCode] 32. Longest Valid Parentheses (2) | 2023.10.31 |