🔟 自定義tabbar
阿新 • • 發佈:2021-10-11
import java.util.Arrays; public class Algorithm { public static void main(String[] args) { int[] nums = {1,0,2,2,1,0,2,0,2,0,0,2,1,1}; new Solution().sortColors(nums); System.out.println(Arrays.toString(nums)); } } class Solution { public void sortColors(int[] nums) { if (nums == null || nums.length == 0) { return; } /** * 三路快速排序法的思路 * 迴圈不變數:arr[0, lt] == 0,arr[lt + 1, i] == 1,arr[gt, nums.length - 1] == 2 */ int lt = -1; int gt = nums.length; int i = lt + 1; while (i < gt) { if (nums[i] == 0){ lt++; swap(nums, lt, i); i++; } else if (nums[i] == 1){ i++; }else { gt--; swap(nums, gt, i); } } } public void swap(int[] arr, int i, int j){ int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }