您的位置:首页 > 其它

刷leetcode:Majority Element

2015-02-12 10:48 274 查看
题号:169
题目

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.

这道题在编程之美中也出现过,也可以扩展为寻找数组出现次数最多的数。方法相似。

这里用了三种方法实现:

方法一:删除不同元素,前后两个指针,比较元素,如果不同,则两个元素都删除,如果相同,则继续向下比较,最后剩下来的肯定是majority element。但是该代码在leetcode无法通过,出现


Submission Result: Time Limit Exceeded

此时的测试用例:
Last executed input:[1,1,1,1,1,1,1,.................................................................................................
即在极端情况下,数组很大,数组中所有的元素都相等的时候,该算法还是会一直进行比较测试,导致超时。

个人认为在数组并不是这么极端的情况下,这种实现方式还是很好的,时间复杂度O(N)

方法二:给数据排序,找到位置为N/2处的值即可。

方法三:最常用的hash,用数值做Map的key,数值出现的次数作为value,如果value>n/2,即找到了majority element。时间复杂度为O(N).

该方法同样适用于求数组中出现次数最多的元素,只需要对上述value进行排序即可。总的时间负责度为:
O(N+N*logN)=O(N*logN),排序的时间复杂度为O(N*logN)。

public class Solution {
public int majorityElement(int[] num) {

if(num.length==1) return num[0];
/** delete different elements  Time:O(n) Space:O(n)
Integer[] numBox=new Integer[num.length];
for(int i=0;i<num.length;i++){
numBox[i]=Integer.valueOf(num[i]);
}
List<Integer> listNum=new LinkedList<Integer>(Arrays.asList(numBox));
int i=0;
int j=listNum.size()-1;
while(i<j){
if(listNum.get(i)!=listNum.get(j)){
listNum.remove(i);
j=j-1;
listNum.remove(j);
j=j-2;
continue;
}
i++;
j--;
}
return listNum.get(0);
**/
/**
Arrays.sort(num);
return num[num.length/2];
**/
//Hash
int majority=0;
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<num.length;i++){
Integer key=Integer.valueOf(num[i]);
if(map.get(key)==null){
map.put(key,1);
}else{
map.put(key,map.get(key)+1);
}
Integer value=map.get(key);
if(value!=null&&value>num.length/2){
majority=num[i];
break;
}
}
System.out.println(majority);
return majority;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: