π‘ LeetCode 35 - Search Insert Position
π‘ LeetCode 35 - Search Insert Position
λ¬Έμ
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.
μ μΆλ ₯ μμ
β μμ 1
1
2
Input: nums = [1,3,5,6], target = 5
Output: 2
β μμ 2
1
2
Input: nums = [1,3,5,6], target = 2
Output: 1
β μμ 3
1
2
Input: nums = [1,3,5,6], target = 7
Output: 4
μ μ½μ‘°κ±΄
1 <= nums.length <= 104
-104 <= nums[i] <= 104
- nums contains distinct values sorted in ascending order.
-104 <= target <= 104
μμ± μ½λ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int searchInsert(int[] nums, int target) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
int left = 0;
int right = nums.length - 1;
// 2. μ΄μ§ νμ
while (left <= right) {
if (nums[left] == target) {
// left κ°κ³Ό λμΌνλ©΄ λ°ν
return left;
} else if (nums[right] == target) {
// right κ°κ³Ό λμΌνλ©΄ λ°ν
return right;
} else {
// mid κ°κ³Ό λμΌνλ©΄ λ°ν
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
}
// 3. λ°ν
return left;
}
}
- λ¬Έμ μμ
O(log n)
μκ° λ³΅μ‘λλ₯Ό νμ©νλ€κ³ νμ¬ μ΄μ§ νμμΌλ‘ μ½λλ₯Ό μμ±νλ€.
This post is licensed under CC BY 4.0 by the author.