您的位置:首页 > 其它

LeetCode-Majority Element

2015-10-22 21:01 375 查看
Problem:

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.

Analysis:

这个题目是要找数组中个数超过一半的元素。

思路很简单,就是给数组排序后查找。但是方法2更简单,直接返回数组最中间的数,想一想的确是这样。这就是算法题的魅力所在。

方法3是多数投票算法,思路是:

时间复杂度: O(n) — Moore投票算法: 我们维护一个当前的候选众数和一个初始为0的计数器。遍历数组时,我们看当前的元素x:

如果计数器是0, 我们将候选众数置为 x 并将计数器置为 1

如果计数器非0, 我们根据x与当前的候选众数是否相等对计数器+1或者-1

一趟之后, 当前的候选众数就是所求众数. 时间复杂度 = O(n).

Anwser1:

public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int temp=nums[0];
int num=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==temp) num++;
else {
temp=nums[i];
num=1;
}
if( num> nums.length/2) return temp;
}
return 0;
}
}


Anwser2:

public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}


Anwser3:

public class Solution {
public int majorityElement(int[] nums) {
int count = 0, val = 1;
for (int num : nums) {
if (count == 0) {
val = num;
count = 1;
}
else if (num == val)
count++;
else
count--;
}
return val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: