33. Search in Rotated Sorted Array / Medium / JavaScript #48
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.
설명
nums를 순회하며k를 찾아서,[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]를 다시[nums[0], nums[1], ..., nums[k-1], nums[k], nums[k+1], ..., nums[n-1]]로 정렬한다.nums를 절반씩 잘라가며 target과 일치하는 값을 찾는 함수_search()를 정의한다.함수는 재귀로 사용할 것이고,
배열과, 그 배열의 첫 번째 요소가 정렬된
nums에서 갖는 인덱스 값(startIndexOfOrigin)을 인자로 받는다.배열의 중간에 있는 값이
target과 같다면 인덱스와startIndexOfOrigin를 더한 값을 반환하고,target보다 크다면target은 그 중간값보다 앞에서 찾을 수 있으니 배열의 앞쪽 절반을_search()의 인자로 넣어 함수를 호출한다.반대로
target이 중간값보다 크다면 배열의 뒷쪽 절반을 다시_search()의 인자로 넣어 함수를 호출한다._search()의 종료 조건은 배열을 더 이상 절반으로 자를 수 없을 때. 즉 배열의 길이가 0이나 1이 될 때.길이가 0인 경우
target과 일치하는 요소가 없으므로-1을 반환길이가 1인 경우 요소의 값을
target과 비교한 후 같다면startIndexOfOrigin, 같지 않다면-1을 반환한다.v를 확인한 후,-1이라면nums엔target이 없다는 뜻이므로 그대로-1을 반환,k === 0(start === 0)이라면 1에서nums를 재정렬하지 않았으므로v를 그대로 반환,그 외의 경우라면 1에서
nums를 정렬하기 전의 인덱스 값을 찾기 위해(v + k) % nums.length를 반환한다.Time Complexity: O(n)
_search()재귀 호출하는 건 nums를 반씩 잘라가며 호출하므로 O(log N)문제 조건이 O(log n)으로 푸는 건데 ㅎ;
좀 더 고민해봐야겠다
Space Complexity: O(1)