赞
踩
给定一个大小为 n
的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
进阶:
import java.util.*; public class MajorityElement{ public static void main(String[] args) { Solution solution = new MajorityElement().new Solution(); System.out.println(solution.majorityElement(new int[]{3,2,3})); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int majorityElement(int[] nums) { Map<Integer,Integer> map = new HashMap(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (map.get(num) == null) { map.put(num,1); }else { int temp = map.get(num)+1; map.put(num,temp); } } Set<Integer> integers = map.keySet(); Iterator iterator = integers.iterator(); while (iterator.hasNext()){ int num = (int) iterator.next(); if (map.get(num) > nums.length/2) return num; } return 0; } } //leetcode submit region end(Prohibit modification and deletion) }
class Solution {
public int majorityElement(int[] nums) {
int cand_num = nums[0], count = 1;
for (int i = 1; i < nums.length; ++i) {
if (cand_num == nums[i])
++count;
else if (--count == 0) {
cand_num = nums[i];
count = 1;
}
}
return cand_num;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。