簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。