34. Find First and Last Position of Element in Sorted Array / Medium / JavaScript #49
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
설명
재귀 함수를 생성한다.
target
과 같으면 양쪽으로 탐색 범위를 넓혀서 값이 같은 min, max 인덱스를 찾아내 반환한다.target
보다 크면 [0 ~ 중간값 -1]의 배열을 대상으로 다시 1번을 수행한다.target
보다 크면 [중간값 + 1 ~ 끝]의 배열을 대상으로 다시 1번을 수행한다.target
과 일치하는 값이 없으므로[-1, -1]
을 반환한다.target
을 비교해[0, 0]
을[-1, -1]
을 반환한다.단, 재귀 함수에 인자로 넣는 배열은 계속 반으로 자른 것이니
인덱스를 반환할 땐 해당 인덱스가 원본 배열에서는 어떤 값인지를 계산해서 반환해야 함
=> 재귀 함수에 인자로 배열을 넣을 때, 해당 배열의 첫 번째 요소가 원본 배열에서는 어떤 인덱스에 있는지(=
originStartIndex
)도 함께 인자로 넣어최종적으로 인덱스를 반환할 때 원본에서의 위치도 계산한다.
예컨대,
[2, 2, 5, 5, 7, 8, 8, 10]에서
target
8을 찾는다면,mid
는 3,nums[3]
은 5, 5 < 8이므로 [7, 8, 8, 10]을 대상으로 다시 1번 수행,originStartIndex
는mid + 1
인 4.mid
는 1,nums[1]
은 8, 8 === 8이므로min
은 1,max
는 2. 최종적으로originStartIndex
더해서[5, 6]
반환Time Complexity: O(log N)
target
을 찾을 때까지 배열을 반으로 잘라 함수를 호출함Space Complexity: O(1)
추가적인 공간을 사용하지 않음