标签:leetcode
题意: 找出一个数组中的主要元素,主要元素为出现次数大于[n/2]的元, 当然最笨的方法就是暴力,没式不知道时间行不行
思路1: 遍历数组,统计每个元素出现的次数,用HashMap统计每个元素出现的次数 时间复杂度O(N),空间复杂度 O(N)
代码1:
public class Solution { public int majorityElement(int[] num) { int majority = 0, currCount; int major = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i< num.length; ++i){ if(m.containsKey(num[i])){ currCount = m.get(num[i]) + 1; if(currCount > major) return num[i]; m.put(num[i], currCount); }else m.put(num[i],1); } return majority; } }
public int majorityElement(int[] num) {//排序 int majority = 0, currCount; int major = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; Arrays.sort(num); return num[num.length/2]; }
public int majorityElement(int[] num) {//摩尔投票算法 int majority = 0, currCounter = 0, candidate = 0; int minCounter = (int) Math.floor( num.length*1.0 / 2 ); if(num.length == 1) return num[0]; for(int i = 0; i < num.length; ++i){ if(currCounter == 0){ candidate = num[i]; currCounter ++; }else { if(candidate == num[i]){ currCounter ++; } else currCounter --; } if(currCounter > minCounter)return candidate; } return candidate; }
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44887689