/** * @param {number[]} nums * @return {number[]} */ var majorityElement = function (nums) { // const limit = ~~(nums.length / 3); // let result = []; // let map = new Map(); // for (let i = 0; i < nums.length; i++) { // if (!map.has(nums[i])) { // map.set(nums[i], 1); // } else { // map.set(nums[i], map.get(nums[i]) + 1); // } // } // for (const [key, val] of map) { // if (val > limit) result.push(key); // } // return result; if (nums.length < 2) return nums; const limit = ~~(nums.length / 3); let num1 = nums[0], num2 = nums[0], count1 = 0, count2 = 0; for (let i = 0; i < nums.length; i++) { const cur = nums[i]; if (cur === num1) { count1++; continue; } if (cur === num2) { count2++; continue; } if (count1 === 0) { num1 = cur; count1 = 1; continue; } if (count2 === 0) { num2 = cur; count2 = 1; continue; } if (cur !== num1 && cur !== num2) { count1--; count2--; } } let result = []; if (count1 && nums.reduce((acc, cur) => acc += cur === num1 ? 1 : 0, 0) > limit) result.push(num1); if (count2 && nums.reduce((acc, cur) => acc += cur === num2 ? 1 : 0, 0) > limit) result.push(num2); return result; };

Use Map

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

var majorityElement = function (nums) { const limit = ~~(nums.length / 3); let result = []; let map = newMap(); for (let i = 0; i < nums.length; i++) { if (!map.has(nums[i])) { map.set(nums[i], 1); } else { map.set(nums[i], map.get(nums[i]) + 1); } } for (const [key, val] of map) { if (val > limit) result.push(key); } return result; };