ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก