Легко Решено: 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. Следуйте условию и ограничениям выше.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.