229. Majority Element II
发布日期:2021-05-04 11:02:46 浏览次数:28 分类:精选文章

本文共 1430 字,大约阅读时间需要 4 分钟。

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]

Output: [3]
Example 2:

Input: [1,1,1,3,3,2,2,2]

Output: [1,2]

来源:力扣(LeetCode)

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

找出出现次数大于n/3的数。

结果肯定是一个或者两个。

先选出两个候选者,再判断它出现的次数是否满足。

 

class Solution {    public List
majorityElement(int[] nums) { int a = 0; int b = 0; int counta = 0; int countb = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == a) { counta++; } else if (nums[i] == b) { countb++; } else if (counta == 0) { a = nums[i]; counta++; } else if (countb == 0) { b = nums[i]; countb++; } else { counta--; countb--; } } counta = 0; countb = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == a) { counta++; } else if (nums[i] == b) { countb++; } } List
ans = new ArrayList<>(); if (counta > nums.length / 3) { ans.add(a); } if (countb > nums.length / 3) { ans.add(b); } return ans; }}

 

上一篇:231. Power of Two
下一篇:222. Count Complete Tree Nodes

发表评论

最新留言

很好
[***.229.124.182]2025年04月10日 02时27分35秒