您的位置:首页 > Web前端 > JavaScript

Majority Element

2016-06-11 01:43 471 查看
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.

Tags:

Array, Divide and Conquer, Bit Manipulation

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

First thought:

Loop the array and using a hash array to count for each character,

If the counter reaches to Math.floor(n/2), return the value.

However, this one will cause the Time Limited Error.

Second try:

Sort the array first,

Loop the array and use one count variable for counting nearby same character.

If the counter reaches to Math.floor(n/2), return the value.

Otherwise reset the counter and restart from a new character.

var majorityElement = function (nums) {
var len = nums.length;
var ret = nums[0];
var counter = 1, i = 0;

nums.sort();

while (i < len - 1) {
if (nums[i] === nums[i + 1]) {
counter++;
if (counter > len / 2) {
ret = nums[i];
break;
}
} else {
counter = 1;
}
i++;
}
return ret;
};

Third Try:

Sort the array, the middle one is the one we are seeking for.

Cause the majority always happen more than Math.floor(n/2) frequency.

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
nums.sort();
return nums[parseInt(nums.length / 2)];
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息