题目
题目要求
直接在nums上排序,不用新的memory,且不使用自带的sort function
解题思路(多指针)
此题为 Dutch national flag problem,使用了三指针i, j, k。其含义和逻辑见代码注释和下图
class Solution:def sortColors(self, nums: List[int]) -> None:# i, index ready to swap where nums[i]<mid is expected at this index# j, current index where nums[j]=mid is expected, if not, swap with index i or index k accordingly# k, index ready tp swap where nums[k]>mid is expected at this indexi = 0j = 0k = len(nums) - 1mid = 1while j<=k:if nums[j] < mid: # swap with index inums[i], nums[j] = nums[j], nums[i]i += 1j += 1elif nums[j] > mid: #swap with index k# j,k has swapped, we need to consider the new nums[j]# so we don't need to do j += 1 herenums[j], nums[k] = nums[k], nums[j]k -= 1else:j += 1
为什么 swap i, j需要 j+= 1, 而swap j,k 确不需要?
通过下面两个例子我们来观察一下i, j, k的变化,以及发现为什么 while j<=k作为循环条件。
当4->5时,首先明白调换之后,新的位置j已经变了,对于这个数我们要重新考量排序, 因此swap(j,k)之后,不应该执行j+=1。其次,到达第5步时,很显然排序并没有结束,所以循环条件是while j<=k而不是while j<k


