Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Second Largest Value

Find the second largest distinct value.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
numbers = [4, 9, 7, 9]

Kết quả mong đợi:
expected = 7
Đầu vào:
std::vector<long long> numbers = {4, 9, 7, 9};

Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long[] numbers = new long[] {4, 9, 7, 9};

Kết quả mong đợi:
long expected = 7;

Giải thích

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

Ví dụ 2
Đầu vào:
numbers = [5, 5]

Kết quả mong đợi:
expected = -1
Đầu vào:
std::vector<long long> numbers = {5, 5};

Kết quả mong đợi:
long long expected = -1;
Đầu vào:
long[] numbers = new long[] {5, 5};

Kết quả mong đợi:
long expected = -1;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.