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

ตรวจสอบว่าอาร์เรย์เรียงได้ด้วยการสลับเพียงครั้งเดียว ใน Python


ปัญหา

ให้อาร์เรย์ ตรวจสอบว่าสามารถเรียงลำดับไม่ลด (non-decreasing) ได้ด้วยการสลับ (swap) เพียง 1 ครั้ง หรือไม่

ตัวอย่าง

input_list = [7, 8, 12, 10, 11, 9]
Sorted: [7, 8, 9, 10, 11, 12]
ตำแหน่งต่างกัน: index 2 (12 vs 9) และ index 5 (9 vs 12) → 2 ตำแหน่ง → swap ได้ → "Can be done"

แนวคิดการแก้ปัญหา

  1. สร้างอาร์เรย์เรียงลำดับ (sorted copy)
  2. นับจำนวนตำแหน่งที่ค่าต่างจาก sorted
  3. ถ้า 0 ตำแหน่ง (เรียงแล้ว) หรือ 2 ตำแหน่ง → สลับได้ → True
  4. อื่นๆ → False

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

from copy import deepcopy

def solve(arr):
    sorted_arr = sorted(arr)
    diff_count = sum(1 for i in range(len(arr)) if arr[i] != sorted_arr[i])
    if diff_count == 0 or diff_count == 2:
        return "Can be done"
    return "Can't be done"

print(solve([7, 8, 12, 10, 11, 9]))  # Can be done

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

Input:  [7, 8, 12, 10, 11, 9]
Output: Can be done