Skip to content

33. Search in Rotated Sorted Array / Medium / JavaScript #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

yeongrok-jeong
Copy link
Contributor

@yeongrok-jeong yeongrok-jeong commented May 4, 2023

설명

  1. 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]]로 정렬한다.
  2. nums를 절반씩 잘라가며 target과 일치하는 값을 찾는 함수 _search()를 정의한다.
    함수는 재귀로 사용할 것이고,
    배열과, 그 배열의 첫 번째 요소가 정렬된 nums에서 갖는 인덱스 값(startIndexOfOrigin)을 인자로 받는다.
    배열의 중간에 있는 값이 target과 같다면 인덱스와 startIndexOfOrigin를 더한 값을 반환하고,
    target보다 크다면 target은 그 중간값보다 앞에서 찾을 수 있으니 배열의 앞쪽 절반을 _search()의 인자로 넣어 함수를 호출한다.
    반대로 target이 중간값보다 크다면 배열의 뒷쪽 절반을 다시 _search()의 인자로 넣어 함수를 호출한다.
  3. _search()의 종료 조건은 배열을 더 이상 절반으로 자를 수 없을 때. 즉 배열의 길이가 0이나 1이 될 때.
    길이가 0인 경우 target과 일치하는 요소가 없으므로 -1을 반환
    길이가 1인 경우 요소의 값을 target과 비교한 후 같다면 startIndexOfOrigin, 같지 않다면 -1을 반환한다.
  4. 재귀함수의 호출 스택이 비워지고 최종적으로 반환된 값 v를 확인한 후,
    -1이라면 numstarget이 없다는 뜻이므로 그대로 -1을 반환,
    k === 0(start === 0)이라면 1에서 nums를 재정렬하지 않았으므로 v를 그대로 반환,
    그 외의 경우라면 1에서 nums를 정렬하기 전의 인덱스 값을 찾기 위해 (v + k) % nums.length를 반환한다.

Time Complexity: O(n)

  • 1에서 정렬하는데 최대 O(n)
  • _search() 재귀 호출하는 건 nums를 반씩 잘라가며 호출하므로 O(log N)

You must write an algorithm with O(log n) runtime complexity.

문제 조건이 O(log n)으로 푸는 건데 ㅎ;
좀 더 고민해봐야겠다

Space Complexity: O(1)

  • 추가적인 공간을 필요로 하지 않음

@yeongrok-jeong yeongrok-jeong self-assigned this May 4, 2023
@yeongrok-jeong yeongrok-jeong requested a review from lynn0506 May 8, 2023 03:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant