您的位置:首页 > 其它

169. Majority Element

2016-11-07 19:56 141 查看

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.

思路一

可以把数组中的元素和元素出现的次数存入到hashmap中,然后遍历数组中的元素,然后把再一次出现的元素的次数刷新。

代码

public class Solution {
public int majorityElement(int[] nums) {
//用hashmap可以实现,每遍历一次,value值加一
//忘记考虑只有一个元素的情况
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < nums.length;i++){
if(map.containsKey(nums[i])){
int num = map.get(nums[i]);
map.put(nums[i],num + 1);
if(num+1 > nums.length/2)
return nums[i];
}
else
map.put(nums[i],1);
}
return nums[0];
}
}


结果及分析

【You are here!

Your runtime beats 12.04% of javasubmissions.】这个结果距离最优还差很多。

思路二

用一个标记count记录某个元素出现的次数,如果后面的元素和它相同就加一,有一个元素和他不相同就减一,当count小于等于0时重新记录新的元素。原文

public class Solution {
public int majorityElement(int[] num) {
int main = num[0]; // 用于记录主元素,假设第一个是主元素
int count = 1; // 用于抵消数的个数
for (int i = 1; i < num.length; i++) {
// 从第二个元素开始到最后一个元素
if (main == num[i]) { // 如果两个数相同就不能抵消
count++; // 用于抵消的数据加1
} else {
if (count > 0) { // 如果不相同,并且有可以抵消的数
count--; // 进行数据抵消
} else { // 如果不相同,并且没有可以抵消的数
main = num[i]; // 记录最后不可以抵消的数
}
}
}
return main;
}
}


结果及分析

【You are here!

Your runtime beats 63.75% of javasubmissions.】

时间复杂度为O(n),空间复杂度为O(1);

二刷解法

解法与前一个解法相同,优化了一些代码的书写方式,最好不要嵌套if,而且更容易理解,当count抵消完的时候,会加入一个新的数字,同时count置为1.

CODE

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