问题描述
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
How many majority elements could it possibly have?
算法思想
最基本也是最简单的两边扫描方法
第一遍扫描原始数组,利用hashmap记录不同元素出现的次数,key存储元素值,value存储次数
第二遍扫描hash,把数目超过1/3的Entry的key加入到返回列表中。
虽然我认为他的空间复杂度为O(n),但这个方法竟然奇迹般的被Accept掉了。
算法实现
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
Map<Integer, Integer> records = new HashMap<Integer,Integer>();
for(int e:nums){
if(records.containsKey(e))
records.put(e,records.get(e)+1);
else
records.put(e,1);
}
Iterator<Entry<Integer,Integer>> it = records.entrySet().iterator();
while(it.hasNext()){
Entry<Integer,Integer> e = it.next();
if(e.getValue() > (nums.length/3)){
list.add(e.getKey());
}
}
return list;
}
public static void main(String [] args){
Solution s = new Solution();
int [] arr = {1,2,3,3,3,3};
List<Integer> list = s.majorityElement(arr);
for(Integer i : list){
System.out.println(i);
}
}
}
算法时间
由于hashMap的containKey方法时间复杂度为O(1),则:
算法时间复杂度,为线性扫描时间O(n)
空间复杂度我认为是O(n)。
演示结果
3