75. Sort Colors
# Medium
Key idea:
2
must be the end, 0
must be the begining.
Record the index of next possible 0
as p0
; record the index of next possible 2
as p2
.
Solution:
if
nums[i] = 0
, swap(nums[p0], nums[i]), p0 and i move forward one stepif
nums[i] = 2
, swap(nums[i], nums[p2]), p2 move back one stepif
nums[i] = 1
, only i move forward one step
最难想的是nums[i] = 1
该怎么处理,跳过即可,但是不能挪p0
指针
Last updated