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:

  1. if nums[i] = 0, swap(nums[p0], nums[i]), p0 and i move forward one step

  2. if nums[i] = 2, swap(nums[i], nums[p2]), p2 move back one step

  3. if nums[i] = 1, only i move forward one step

Time complexity = O(n)O(n) , space complexity = O(1)O(1)

Last updated

Was this helpful?