您的位置:首页 > 其它

[LeetCode] Majority Element

2015-08-13 14:02 232 查看
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.

这道题其实可以用比较取巧的方法做。因为在这里marjority element的定义是整个数列中至少一半的数字都是它,所以当我们sorting了整个数列,中间的那个数肯定是Marjority element。所以非常简单,考虑下length为1的特殊情况就可。代码如下。

public class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1){
return nums[0];
}

Arrays.sort(nums);
return nums[nums.length/2];
}
}


当然了还有比较常规的,老实按照loop来计算的。这个思路就很简单了。代码如下。

public class Solution {
public int majorityElement(int[] num) {
if(num.length==1){
return num[0];
}

Arrays.sort(num);

int test=num[0];
int count=1;
for(int i=1; i<num.length; i++){
if(num[i] == test){
count++;
if(count > num.length/2)
return num[i];
}else{
count=1;
test = num[i];
}
}

return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: