ปัญหา
กำหนด 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
แนวทางแก้ปัญหา
- นับความถี่ทุกค่า (
freq) - เรียงลำดับตามค่าสัมบูรณ์ (
key=abs) - จับคู่ค่า
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