Sort Colors 解决方案
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Could you come up with an one-pass algorithm using only constant space?
解这道题,也可以再学习下 计数排序
public void sortColor(int[] nums) {
if(nums == null || nums.length <= 1) {
return;
}
int low = 0;
int high = nums.length - 1;
for(int i = low; i <= high;) {
if(nums[i] == 0) {
int temp = nums[i];
nums[i] = nums[low];
nums[low] = temp;
i++;
temp++;
} else if(nums[i] == 2) {
int temp = nums[i];
nums[i] = nums[high];
nums[high] = temp;
high--;
} else {
i++;
}
}
}
- ← Previous
解读 word2vec 项目 - Next →
URLDecoder 处理文件的 case 小记