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
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1: 输入: [3,2,3] 输出: 3
示例 2: 输入: [2,2,1,1,1,2,2] 输出: 2
var majorityElement = function(nums) { var map = new Map(); nums.forEach(function(item){ var result = map.get(item) ? map.get(item)+1 : 1 map.set(item, result) }); var max = 0; var target; map.forEach(function(item, key){ if(item>max){ max = item; target = key } }); return target };
/** * @param {number[]} nums * @return {number} */ var majorityElement = function(nums) { var count=0; var result; for(var i=0;i<nums.length;i++){ if(count==0){ result = nums[i] } if(nums[i]===result){ count++ }else{ count-- } } return result };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
投票法
The text was updated successfully, but these errors were encountered: