75.颜色分类
方法一:使用单指针
class Solution {public void sortColors(int[] nums) {int n = nums.length;int ptr = 0;for(int i = 0;i<n;i++){if(nums[i] == 0){int tmp = nums[i];nums[i] = nums[ptr];nums[ptr] = tmp;++ptr;}}for(int i = ptr;i<n;i++){if(nums[i] == 1){int tmp = nums[i];nums[i] = nums[ptr];nums[ptr] = tmp;++ptr;}}}
}
方法二:使用双指针
class Solution {public void sortColors(int[] nums) {int n = nums.length;int p0 = 0, p2 = n - 1;for (int i = 0; i <= p2; ++i) {while (i <= p2 && nums[i] == 2) {int temp = nums[i];nums[i] = nums[p2];nums[p2] = temp;--p2;}if (nums[i] == 0) {int temp = nums[i];nums[i] = nums[p0];nums[p0] = temp;++p0;}}}
}