多数元素

题目描述:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:HashMap

利用java的HashMap,key存不同的数字,value存对应的数字出现的次数:

  • 遍历nums,将每个数字放入HashMap里;
  • 比较得到的HashMap,比较每个数字出现的次数,得到出现次数最多的数字,返回结果。

解法二:摩尔投票算法

摩尔投票算法就是把相异的2个数都消耗掉,由于总是存在多数元素,意味着相异的数消耗掉之后只可能留下那个多数元素。具体过程如下,用result记录最终的那个多数,初始化为数组的第一个元素,count记录这个数字重复的次数:

  • 首先,如果count为0,表示前面的相异的数字都消耗完了,result赋值为当前的数,count为1;
  • 如果count大于0:
    • 如果result和当前元素相等,则count加1;
    • 如果result和当前元素不相等,则count减一,即消耗掉一对相异的数。

最终result一定是那个多数元素。

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class LeetCode_169 {
  4. /**
  5. * 方法一:HashMap
  6. *
  7. * @param nums
  8. * @return
  9. */
  10. public static int majorityElement(int[] nums) {
  11. Map<Integer, Integer> count = new HashMap<>();
  12. for (int num : nums) {
  13. if (count.get(Integer.valueOf(num)) == null) {
  14. count.put(Integer.valueOf(num), 1);
  15. } else {
  16. count.put(Integer.valueOf(num), count.get(Integer.valueOf(num)) + 1);
  17. }
  18. }
  19. int result = -1, maxCount = -1;
  20. for (Map.Entry<Integer, Integer> integerIntegerEntry : count.entrySet()) {
  21. if (integerIntegerEntry.getValue() > maxCount) {
  22. maxCount = integerIntegerEntry.getValue();
  23. result = integerIntegerEntry.getKey();
  24. }
  25. }
  26. return result;
  27. }
  28. /**
  29. * 方法二:摩尔投票算法
  30. *
  31. * @param nums
  32. * @return
  33. */
  34. public static int majorityElement2(int[] nums) {
  35. int result = nums[0], count = 1;
  36. for (int i = 1; i < nums.length; i++) {
  37. if (count == 0) {
  38. result = nums[i];
  39. count++;
  40. } else {
  41. if (result == nums[i]) {
  42. count++;
  43. } else {
  44. count--;
  45. }
  46. }
  47. }
  48. return result;
  49. }
  50. public static void main(String[] args) {
  51. int[] nums = new int[]{10, 9, 9, 9, 10};
  52. System.out.println(majorityElement(nums));
  53. System.out.println(majorityElement2(nums));
  54. }
  55. }

【每日寄语】 所有逆袭,都是有备而来;所有光芒,都是努力埋下的伏笔。