Skip to content

34. Find First and Last Position of Element in Sorted Array / Medium / JavaScript #49

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

설명

재귀 함수를 생성한다.

  1. 중간값을 찾은 후
    1. target과 같으면 양쪽으로 탐색 범위를 넓혀서 값이 같은 min, max 인덱스를 찾아내 반환한다.
    2. 중간값이 target보다 크면 [0 ~ 중간값 -1]의 배열을 대상으로 다시 1번을 수행한다.
    3. 중간값이 target보다 크면 [중간값 + 1 ~ 끝]의 배열을 대상으로 다시 1번을 수행한다.
  2. 재귀 함수의 종료 조건은
    1. 배열 길이가 0이라면 배열 내에 target과 일치하는 값이 없으므로 [-1, -1]을 반환한다.
    2. 배열 길이가 1이라면 배열 내 유일한 값과 target을 비교해
      1. 같다면 [0, 0]
      2. 다르다면 [-1, -1]을 반환한다.

단, 재귀 함수에 인자로 넣는 배열은 계속 반으로 자른 것이니
인덱스를 반환할 땐 해당 인덱스가 원본 배열에서는 어떤 값인지를 계산해서 반환해야 함
=> 재귀 함수에 인자로 배열을 넣을 때, 해당 배열의 첫 번째 요소가 원본 배열에서는 어떤 인덱스에 있는지(= originStartIndex)도 함께 인자로 넣어
최종적으로 인덱스를 반환할 때 원본에서의 위치도 계산한다.

예컨대,
[2, 2, 5, 5, 7, 8, 8, 10]에서 target 8을 찾는다면,

  1. mid는 3, nums[3]은 5, 5 < 8이므로 [7, 8, 8, 10]을 대상으로 다시 1번 수행, originStartIndexmid + 1인 4.
  2. mid는 1, nums[1]은 8, 8 === 8이므로 min은 1, max는 2. 최종적으로 originStartIndex 더해서 [5, 6] 반환

Time Complexity: O(log N)

target을 찾을 때까지 배열을 반으로 잘라 함수를 호출함

Space Complexity: O(1)

추가적인 공간을 사용하지 않음

@yeongrok-jeong yeongrok-jeong requested a review from lynn0506 May 9, 2023 14:27
@yeongrok-jeong yeongrok-jeong self-assigned this May 9, 2023
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