我想使用ArrayList对nums []进行排序,但它只能传递17/83个案例。我不知道我做错了什么。
public class Solution {
public void sortColors(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> redList = new ArrayList<Integer>();
List<Integer> whiteList = new ArrayList<Integer>();
List<Integer> blueList = new ArrayList<Integer>();
if(nums==null||nums.length==0)
return ;
for(int number:nums){
switch (number){
case 0:
redList.add(number);
break;
case 1:
whiteList.add(number);
break;
case 2:
blueList.add(number);
break;
default:
break;
}
}
list.addAll(redList);
list.addAll(whiteList);
list.addAll(blueList);
}
}
它占用了大量的额外空间,但我认为它可以比插入排序更快。
答案 0 :(得分:0)
检查API到期Collections.sort
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
//Must be Integer class
Integer[] nums = { 1, 2, 3, 0, 1, 2, 3, 1, 4, 4, 4, 0, 0, 1, 2, 1, 0,
0, 4 };
List<Integer> list = Arrays.asList(nums);
// Before sort
System.out.println("Before sort :" + list.toString());
// Sort 'list' items
Collections.sort(list);
// After sort
System.out.println("After sort :" + list.toString());
}
输出:
Before sort :[1, 2, 3, 0, 1, 2, 3, 1, 4, 4, 4, 0, 0, 1, 2, 1, 0, 0, 4]
After sort :[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4]