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

โปรแกรมตรวจสอบ Array เรียงแล้วหมุน (Sorted and Rotated) ใน Python

โจทย์

มีอาร์เรย์ nums ต้องตรวจสอบว่ามันเคยถูกเรียงลำดับ Non-decreasing แล้วหมุน (Rotate) ไปจำนวนหนึ่ง (อาจ 0) หรือไม่ อาจมีค่าซ้ำได้

ตัวอย่าง: nums = [12,15,2,5,6,9] → True (หมุนขวา 2 ตำแหน่ง จาก [2,5,6,9,12,15])

อัลกอริธึม

  1. หาจุดที่ลำดับแตก (หา j ที่ nums[j] > nums[j+1])
  2. รวม Subarray หลังจุดแตก + Subarray ก่อนจุดแตก → res
  3. ตรวจสอบ res ว่าเรียง Non-decreasing ทั้งหมดหรือไม่

โค้ด Python


def solve(nums):
    j = 0
    while j < len(nums) - 1 and nums[j] <= nums[j + 1]:
        j += 1
    res = nums[j + 1:] + nums[:j + 1]
    for i in range(len(res) - 1):
        if res[i] > res[i + 1]:
            return False
    return True

nums = [12, 15, 2, 5, 6, 9]
print(solve(nums))  # Output: True

Input / Output

Input:  [12,15,2,5,6,9]
Output: True