쉬움 0명 해결 정답률 0%

Second Largest Value

Find the second largest distinct value.

배우게 될 내용

  • Track the top two values in one pass
  • Ignore duplicates of the maximum
  • Handle lists without a second value

문제

번역본 보기

Return the second largest distinct value in the list. Repeated values count once.

Implement second_largest(numbers).

Input

numbers: A list of non-negative integers.

Output

Return the second largest distinct value, or -1 if it doesn't exist.

제약 조건

0 ≤ length ≤ 100,000; 0 ≤ each value ≤ 10⁹

예시

예시 1
입력:
numbers = [4, 9, 7, 9]

예상 출력:
expected = 7
입력:
std::vector<long long> numbers = {4, 9, 7, 9};

예상 출력:
long long expected = 7;
입력:
long[] numbers = new long[] {4, 9, 7, 9};

예상 출력:
long expected = 7;

설명

Distinct values are 9, 7, 4; the second largest is 7.

예시 2
입력:
numbers = [5, 5]

예상 출력:
expected = -1
입력:
std::vector<long long> numbers = {5, 5};

예상 출력:
long long expected = -1;
입력:
long[] numbers = new long[] {5, 5};

예상 출력:
long expected = -1;

설명

Only one distinct value exists, so the answer is -1.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

You need the largest and the next different value, not just the top two positions.

힌트 2

Track two distinct maxima as you scan, updating them when a new value fits above or between them.

힌트 3

If no second distinct value ever appears, return the special fallback value.

예상 복잡도

O(n) time, O(1) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.