问题:
难度:easy
说明:
这次就用到hash排序了吧,当然也可以不用毕竟不是最优,问题是给出乱序的0,1,2数组代表三种颜色(并没有什么意义),然后要求排序从小到大0,1,2。
问题链接:https://leetcode.com/problems/sort-colors/
相关问题:
蜗牛型排序:https://blog.csdn.net/qq_28033719/article/details/105997980
奇偶链表排序:https://blog.csdn.net/qq_28033719/article/details/105011709
输入案例:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
我的代码:
很简单的排序,水题,题目提示里面要求你只用1-pass处理,我写个2-pass的。
class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length < 2) return;
int len = nums.length;
int[] map = new int[3];
// 将0,1,2全部存到hashmap里面
for(int i = 0;i < len;i ++) {
map[nums[i]] ++;
}
// 弄一个map数组的索引
int index = 0;
// 然后把map里面的统计数值,将nums重新赋值
for(int i = 0;i < nums.length;i ++) {
while(map[index] == 0) index ++;
nums[i] = index;
-- map[index];
}
}
}
1-pass的,就是想像数组原来是空的,然后自己重新添加东西进去就是
class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length < 2) return;
int len = nums.length;
int low = 0;
int mid = 0;
int high = len - 1;
while(mid <= high){
if(nums[mid] == 0){
swap(nums, low, mid);
low++;
mid++;
}
else if(nums[mid] == 1){
mid++;
}
else if(nums[mid] == 2){
swap(nums, mid, high);
high--;
}
}
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}