您的位置:首页 > 其它

LeetCode__169. Majority Element

2016-01-11 21:02 375 查看
169. Majority Element

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.
如题,给定一个数组,找出其中元素个数超过一半的数,
本来写不好,但是后面有一个假设,及这样的数数组中一定存在,这样难度就大大降低了。

借鉴了上一个程序:

public class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1) return nums[0];
Arrays.sort(nums);
int sum = 1;
for(int i = 0; i <nums.length-1; i++){
if(nums[i]==nums[i+1]){
sum++;
}else{
sum = 1;
}
if(sum>nums.length/2){
return nums[i];
}
}
return nums[0];//这个我不想加,但是必须要返回值,所以……
}
}

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