您的位置:首页 > 其它

169MajorityElement

2016-06-03 17:04 225 查看
题目: 找到数组中元素出现次数过半的元素,已知条件:数组非空,必定存在符合条件的元素

思路: 数组排序,扫描的过程中计数并发现目标元素

public class Solution {
//prerequisition: non-empty and majority exits
public int majorityElement(int[] nums) {
if(nums.length == 1)
return nums[0];
Arrays.sort(nums); //O(log(n))
int num = 1;
int majorty = nums.length/2 + 1;
int i;
for(i = 1; i < nums.length; i++){
if(nums[i] == nums[i-1])
num++;
else
num = 1;
if(num >= majorty)
break;//obsolutely
}
return  nums[i];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: