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

ตรวจสอบว่าแอรเรย์เรียงแล้วและหมุน (sorted and rotated) หรือไม่ใน Python

ภาพรวม

บทความนี้ตรวจสอบว่าแอรเรย์ที่มีค่าไม่ซ้ำกัน เป็น "แอรเรย์ที่เรียงแล้วและหมุน" (sorted and rotated) หรือไม่ โดยต้องมีการหมุนอย่างน้อย 1 ครั้ง (แอรเรย์เรียงสมบูรณ์ไม่นับ)

คุณสมบัติของ Sorted and Rotated Array

  • มีจุดที่ค่าต่ำสุด (min) อยู่ที่ตำแหน่งหนึ่ง
  • ส่วนก่อน min เรียงเพิ่มขึ้น
  • ส่วนหลัง min เรียงเพิ่มขึ้น
  • 元素 สุดท้าย < 元素 แรก (เพราะหมุนทวนเข็มนาฬิกา)

อัลกอริทึม

  1. หาค่าต่ำสุดและดัชนีของมัน
  2. ตรวจสอบส่วนก่อน min ว่าเรียงเพิ่มขึ้นหรือไม่
  3. ตรวจสอบส่วนหลัง min ว่าเรียงเพิ่มขึ้นหรือไม่
  4. ตรวจสอบว่า nums[-1] < nums[0]

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

def solve(nums):
    min_element = min(nums)
    min_index = nums.index(min_element)
    before_sorted = True
    for i in range(1, min_index):
        if nums[i] < nums[i-1]:
            before_sorted = False
            break
    after_sorted = True
    for i in range(min_index+1, len(nums)):
        if nums[i] < nums[i-1]:
            after_sorted = False
            break
    if before_sorted and after_sorted and nums[-1] < nums[0]:
        return True
    return False

nums = [4,5,6,8,1,3]
print(solve(nums))  # True (หมุน 2 ครั้งได้ [1,3,4,5,6,8])

ผลลัพธ์

True

คำอธิบายเพิ่มเติม

ตัวอย่าง [4,5,6,8,1,3] มี min = 1 ที่ดัชนี 4 ส่วนก่อน (4,5,6,8) เรียง เพิ่ม ส่วนหลัง (3) เรียง เพิ่ม และ 3 < 4 จึงเป็น sorted and rotated