Leetcode75 颜色分类
思路比较简单,可以采用计数法,不知为何会被分为中等。
JAVA:
public final void sortColors(int[] nums) { int num0 = 0; int num1 = 0; int num2 = 0; for (int i = 0; i < nums.length; i++) { int curr = nums[i]; if (curr == 0) { num0++; } else if (curr == 1) { num1++; } else { num2++; } } build(0, num0, 0, nums); build(num0, num0 + num1, 1, nums); build(num0 + num1, nums.length, 2, nums); } private final void build(int begin, int end, int target, int[] nums) { for (int i = begin; i < end; i++) { nums[i] = target; } }
JS:
var sortColors = function (nums) { let num0 = 0; let num1 = 0; let num2 = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] == 0) { num0++; } else if (nums[i] == 1) { num1++; } else { num2++; } } build(0, num0, 0, nums); build(num0, num0 + num1, 1, nums); build(num0 + num1, nums.length, 2, nums); }; var build = function (begin, end, target, arr) { for (let i = begin; i < end; i++) { arr[i] = target; } }
当你看清人们的真相,于是你知道了,你可以忍受孤独