[LeetCode] Sort Colors
The hints on below the problem have suggested a two-pass solution.
Now I will focus on the one-pass solution.
The one-pass solution has no mystery. Just swap all 0's to the left and all 2's to the right and the 1's will automatically fall in the middle.
Now comes the following code. You may play with it using some examples on a paper to see how it works.
1 void sortColors(vector<int>& nums) { 2 int red = 0, blue = nums.size() - 1; 3 for (int i = 0; i <= blue; i++) { 4 while (nums[i] == 2 && i < blue) 5 swap(nums[i], nums[blue--]); 6 while (nums[i] == 0 && i > red) 7 swap(nums[i], nums[red++]); 8 } 9 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步