Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:这道题主要是要记录元素出现的次数,相同的元素记做同一个,出现一次则+1,最后看数组中是否有意个大于n/2de数
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var list=[];
for(var i=0; i<nums.length; i++){
if(!list[nums[i]]){
list[nums[i]] = 1;
}
else {
list[nums[i]]++;
}
if(list[nums[i]]>nums.length/2){
return nums[i];
}
}
};