荷兰国旗问题
(??國旗問題) 給定一個列表,和一個數num,請把小于num的數放在列表的左邊,等于num的數放在列表的中間,大于num的數放在列表的右邊。空間復雜度O(1),時間復雜度O(N)
主要思路是給出四個索引:l ,less = l-1? , r , more = r +1
判斷如果左側大于num,則和右側換
def partition(L,l,r,num):less = l - 1more = r + 1while l < more:if L[l] < num:less += 1swap(L,less,l)l +=1elif L[l] > num:more -=1swap(L,more,l)l +=1else:l +=1def swap(L,i,j):temp = L[i]L[i] = L[j]L[j] = temp?
總結
- 上一篇: 逆序对问题
- 下一篇: 设计一个有getMin功能的栈 (pyt