/*****************************************************问题描述*************************************************
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
找出给定数组中出现次数大于数组长度一半的那个元素
/*****************************************************我的解答*************************************************
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var numCountInArray = function(arr,num){
var count = 0;
arr.forEach(function(item){
if(item == num)
{
count++;
}
});
return count;
};
for(var index = 0; index < nums.length; index++)
{
if(numCountInArray(nums,nums[index]) > nums.length / 2)
{
return nums[index];
}
}
};
leetCode刷题记录26_169_Majority Element
最新推荐文章于 2020-09-07 10:48:56 发布