您的位置:首页 > 其它

Leetcode - Majority Element

2016-04-30 19:24 381 查看

Question

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.

Java Code

//版本一:使用map容器,统计并记录每个元素的个数
public int majorityElement(int[] nums) {
//将数组的每个元素及其对应的个数构成<key,value>对,存入map容器
HashMap<Integer, Integer> map = new HashMap<>();
int threshold = nums.length / 2;
int tempCount = 1;
for(int ele : nums) {
//如果该元素已经存在于map中,判断该元素的个数是否超过半数
//如果已经达到半数,即找到了Majority Element,否则将其个数加1
if(map.containsKey(ele)) {
if((tempCount = map.get(ele) + 1) > threshold)
return ele;
map.put(ele, tempCount);
}else
map.put(ele, 1);
}

//如果nums数组中只有一个元素,则直接返回该元素(否则该语句不会被执行)
return nums[0];
}

//版本二:将数组排序,使相同元素挨在一起,再统计各个元素的个数
public int majorityElement2(int[] nums) {
//将原数组排序
Arrays.sort(nums);

int tempCount = 1;
int tempNum = nums[0];
int len = nums.length - 1;
for(int i = 1; i < len; ++i) {
//统计当前元素出现的次数
tempNum = nums[i];
tempCount = 1;
while(i < len && tempNum == nums[i+1]) {
i++;
tempCount++;
}

//已知Majority Element必存在且唯一,如果满足条件则终止遍历
if(tempCount >= len/2) break;
}

return tempNum;
}


说明

版本一代码中使用了HashMap集合,这个解法比较容易想到,但是效率不太高。

版本二代码中对数组进行了排序,使得元素个数的统计变得容易了,但由于进行了排序,所以算法复杂度也不是很低。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode majority array