题目链接
思路
题目要求按0、1、2的顺序排序,因为数量有限,所以通过两次遍历,分别将0和1交换到合适的位置,这样两次遍历之后,剩下的2就都在尾部了。
代码
class Solution {
public void sortColors(int[] nums) {
int p = 0;
for (int circle = 0; circle < 2; ++circle) {
for (int i = p; i < nums.length; i++) {
// circle == 0 or 1
// when circle == 0, we should move 0 to nums' head
// when circle == 1, we should move 1 to nums' middle
if (circle == nums[i]) {
int temp = nums[i];
nums[i] = nums[p];
nums[p] = temp;
++p;
}
}
}
}
}
标签:nums,int,++,75,circle,排序,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17017888.html