We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
169. 多数元素
/** * @param {number[]} nums * @return {number} */ // 普通方法 var majorityElement = function (nums) { const map = {}; let res; for (let i = 0; i < nums.length; i++) { map[nums[i]] = (map[nums[i]] || 0) + 1; if (map[nums[i]] > nums.length / 2) { res = nums[i] } } return res; }; // 抵消法 const majorityElement = nums => { let count = 1; // 遍历从下标1的元素开始, 于是给count设置1 let majority = nums[0]; // 初始值给第一个元素 for (let i = 1; i < nums.length; i++) { // 如果次数被抵消完, 说明等于majority和不等于majority的一样多 if (count === 0) { majority = nums[i]; } if (nums[i] === majority) { // 重复的就+1 count++; } else { // 不重读就抵消count count--; } } return majority; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
169. 多数元素
The text was updated successfully, but these errors were encountered: