LeetCode算法练习Majority Element

来源:互联网 发布:windows多进程编程 编辑:程序博客网 时间:2024/06/07 13:52

       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.
大致意思是找到数组中出现次数在超过50%的元素,在实际中统计学里会用到很多。这个问题我的第一思路是想到了n/2这个关键点的信息,如果想要一个元素出现次数超过n/2,那么在有序的前提下,第n/2元素必为该元素。


public   int majorityElement(int[] num) {int len  = num.length;List<Integer> list  = new ArrayList<Integer>();for (int i : num) {list.add(i);}Collections.sort(list);int temp = list.get((list.size()-1)/2);int count = 1;for (Integer integer : list) {if(temp == integer){count++;}}return count>len/2?temp:0;       
 }


0 0
原创粉丝点击