题目说明
- 数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回
-1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。
示例
示例 1:
1 2
| 输入:[1,2,5,9,5,9,5,5,5] 输出:5
|
示例 2:
示例 3:
笔者理解
此题是一道数组算法问题,在力扣题库中被定义为简单题。
解法
当笔者阅读完此题后,笔者采用了,正反向选举的方式,如果一个数的出现超过半数,那么肯定他出现的次数可以抵消掉其他所有出现的数的次数,依照此规律,我们仅需两次遍历就可以把主要元素找出来,让我们来看看具体如何实现的吧。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| class Solution {
public int majorityElement(int[] nums) { int n = nums.length;
int result = 0;
int mostNum = 0; int mostCount = 0; for (int i = 0; i < n; i++) { if (mostCount == 0) { mostNum = nums[i]; mostCount++; } else { if (mostNum == nums[i]) { mostCount++; } else { mostCount--; } } }
if (mostCount == 0) { return -1; }
result = mostNum; mostNum = 0; mostCount = 0;
for (int i = n - 1; i >= 0; i--) { if (mostCount == 0) { mostNum = nums[i]; mostCount++; } else { if (mostNum == nums[i]) { mostCount++; } else { mostCount--; } } }
if (mostCount == 0 || result != mostNum) { return -1; }
return result; } }
|
时间空间效率都还行,可见此解法还比较适合此题;

总结
本题是今天的每日一题,难度是为简单,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。