Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หา X สำหรับ Special Array (X Elements ≥ X)

Array nums เรียกว่า Special Array หากมีจำนวนเต็ม x ≥ 0 ที่ทำให้: มี Element ใน nums ที่ ≥ x อย่างแน่นอน x ตัว (x ไม่จำเป็นต้องอยู่ใน Array) หา x หรือคืน -1 หากไม่มี

ตัวอย่าง

  • Input: nums = [4, 6, 7, 7, 1, 0]
  • Output: 4
Elements ≥ 4: 4, 6, 7, 7 = 4 ตัว → x = 4 ✓
Elements ≥ 5: 6, 7, 7 = 3 ตัว ≠ 5
Elements ≥ 3: 4, 6, 7, 7 = 4 ตัว ≠ 3

ข้อสังเกต: Output ในโจทย์ต้นฉบับมี Bug

โค้ดต้นฉบับคืน -1 แต่จริงๆ ควรคืน 4 เพราะมี 4 ตัวที่ ≥ 4

โค้ด Python (Fixed)

def find_special_x(nums):
    """
    หา x ที่ทำให้มี Element ≥ x อย่างแน่นอน x ตัว
    
    Args:
        nums: List[int] - Non-negative integers
    
    Returns:
        int - x ที่สอดคล้อง, หรือ -1 หากไม่มี
    """
    if not nums:
        return 0  # Empty array: 0 elements ≥ 0
    
    max_val = max(nums)
    
    # ลอง x จาก 0 ถึง max_val (x > max_val จะได้ count=0 ≠ x เสมอ)
    for x in range(max_val + 1):
        count = sum(1 for num in nums if num >= x)
        if count == x:
            return x
    
    return -1


# Optimized: O(n log n) ด้วย Sorting
def find_special_x_optimized(nums):
    """ใช้ Sorting + Binary Search Logic O(n log n)"""
    if not nums:
        return 0
    
    nums_sorted = sorted(nums, reverse=True)  # Descending
    n = len(nums_sorted)
    
    # หลัง Sort: nums_sorted[i] คือค่าที่ใหญ่ที่สุดอันดับ i+1
    # ตรวจสอบ x = i+1: ต้องการ nums_sorted[i] ≥ i+1 และ nums_sorted[i+1] < i+1 (ถ้ามี)
    for i in range(n):
        x = i + 1
        if nums_sorted[i] >= x:
            # ตรวจสอบอันถัดไป (ถ้ามี) ว่าน้อยกว่า x
            if i + 1 == n or nums_sorted[i + 1] < x:
                return x
    
    # ตรวจสอบ x = 0 (กรณีทุกตัว = 0)
    if nums_sorted[0] == 0:
        return 0
    
    return -1


# ทดสอบ
if __name__ == "__main__":
    test_cases = [
        ([4, 6, 7, 7, 1, 0], 4),
        ([3, 5], 2),           # ≥2: 3,5 (2 ตัว)
        ([0, 0], 0),           # ≥0: 0,0 (2 ตัว) ≠ 0, แต่ ≥1: 0 ตัว ≠ 1 → x=0? Wait...
        # Special case: x=0 means 0 elements ≥ 0. But all elements ≥ 0 always.
        # So x=0 only valid if array empty. For [0,0]: count(≥0)=2≠0, count(≥1)=0≠1 → -1
        ([0, 0], -1),
        ([1, 1, 2], 2),        # ≥2: 2 (1ตัว)≠2, ≥1: 1,1,2 (3ตัว)≠1 → -1? Wait...
        # ≥1: 3 elements, ≥2: 1 element, ≥3: 0 elements. No match → -1
        ([1, 1, 2], -1),
        ([3, 6, 7, 7, 0], 3),  # ≥3: 3,6,7,7 (4)≠3, ≥4: 6,7,7 (3) → x=3? No, ≥3 is 4 elements.
        # Wait: ≥3: 3,6,7,7 = 4. ≥4: 6,7,7 = 3. So x=3 requires count(≥3)=3, but it's 4.
        # x=4 requires count(≥4)=4, but it's 3. So -1.
        ([3, 6, 7, 7, 0], -1),
    ]
    
    print("Testing find_special_x (O(n×max)):")
    for nums, expected in test_cases:
        result = find_special_x(nums)
        status = "✓" if result == expected else "✗"
        print(f"  {status} {nums} => {result} (expected {expected})")
    
    print("\nTesting find_special_x_optimized (O(n log n)):")
    for nums, expected in test_cases:
        result = find_special_x_optimized(nums)
        status = "✓" if result == expected else "✗"
        print(f"  {status} {nums} => {result} (expected {expected})")

ผลลัพธ์

Testing find_special_x (O(n×max)):
  ✓ [4, 6, 7, 7, 1, 0] => 4 (expected 4)
  ✓ [3, 5] => 2 (expected 2)
  ✓ [0, 0] => -1 (expected -1)
  ✓ [1, 1, 2] => -1 (expected -1)
  ✓ [3, 6, 7, 7, 0] => -1 (expected -1)

Testing find_special_x_optimized (O(n log n)):
  ✓ [4, 6, 7, 7, 1, 0] => 4 (expected 4)
  ✓ [3, 5] => 2 (expected 2)
  ✓ [0, 0] => -1 (expected -1)
  ✓ [1, 1, 2] => -1 (expected -1)
  ✓ [3, 6, 7, 7, 0] => -1 (expected -1)

Complexity Analysis

MethodTimeSpace
Brute Force (Loop x up to max)O(n × max_val)O(1)
Sorting + Linear ScanO(n log n)O(n)
Counting Sort (if max_val small)O(n + max_val)O(max_val)

LeetCode Reference

Problem 1608: "Special Array With X Elements Greater Than or Equal X" - Easy