LeetCode 169. Majority Element

来源:互联网 发布:会计软件有哪些 编辑:程序博客网 时间:2024/05/30 22:56

问题:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

问题描述:

找出当前数组中出现的次数最多的,其中最多的那个数出现的次数一定超过[n/2].


问题分析:

这个这个问题如果用一般的方法做就是先用一个Map统计出每个数值出现的次数,然后找出最大的那一个。

但是这个问题中添加了一个额外的条件是  出现最多的数出现的次数超过了[n/2].

这样就有一种额外的解法:

找出两个不同的数都减一,知道最后剩下的哪个数。由于出现最多的数出现的次数超过了[n/2].那么无论如何排列进行减,最终留下的一定是出现最多的哪个数。


代码实现:

  if (nums == null || nums.length == 0) {            return 0;        }        int maxCount = 0;        int num = -1;        for (int i = 0; i < nums.length; i++) {            if (maxCount == 0) {                num = nums[i];                maxCount = 1;            } else if (num != nums[i]) {                maxCount--;            } else {                maxCount++;            }        }        return num;

正常解法是先统计,然后进行找出出现次数最多的解法 。这里用了一种做减法的思路,同时由于有了>[n/2]这个条件使得这种实现变得正常。

原创粉丝点击