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

วิธีตรวจสอบว่า Array จัดเรียงได้ตามเงื่อนไข nums[2*i+1] = 2*nums[i] ใน Python

ปัญหา

กำหนด Array nums ตรวจสอบว่าจัดเรียงใหม่ได้หรือไม่ ที่ทำให้ nums[2*i + 1] == 2 * nums[i] สำหรับทุก i

ตัวอย่าง: [8, -4, 4, -8] → เรียงเป็น [-4, -8, 4, 8] → i=0: -8=2*(-4), i=1: 8=2*4 → True

แนวทางแก้ปัญหา

  1. นับความถี่ทุกค่า (freq)
  2. เรียงลำดับตามค่าสัมบูรณ์ (key=abs)
  3. จับคู่ค่า x กับ 2*x ลดความถี่ทีละ 1

ตัวอย่างโค้ด

from collections import defaultdict

def solve(nums):
    freq = defaultdict(int)
    for x in nums: freq[x] += 1
    for x in sorted(nums, key=abs):
        if freq[x] == 0: continue
        if freq[2*x] == 0: return False
        freq[x] -= 1
        freq[2*x] -= 1
    return True

nums = [8, -4, 4, -8]
print(solve(nums))  # True

อินพุต / เอาต์พุต

Input: [8, -4, 4, -8]
Output: True