Post

πŸ’‘ 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.