应该是用各种排序算法都行的吧
但是效果并不是很好,是可以优化的吧。
public void sortColors(int[] nums) { int n = nums.length; for(int i = 0;i<n;i++){ for(int j =i;j<n;j++){ if(nums[i]>nums[j]){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } }
看了别人的巧妙的答案,相当于使用了双指针吧,或者是三个指针
public void sortColors(int[] nums) { //这算是双指针,三个 int curr = 0, i = 0, j = nums.length - 1; while (curr <= j) { if (nums[curr]==0){ swap(nums, i, curr); i++; curr++; }else if (nums[curr]==1){ curr++; }else { swap(nums, j, curr); j--; } } } public void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }
——2020.7.6