Leetcode 题目解析之 Majority Element II
【摘要】 Leetcode 题目解析之 Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Hint:
- How many majority elements could it possibly have?
- Do you have a better hint? Suggest it!
因为题目中说是大于⌊ n/3 ⌋次数的元素,这样的元素最多只能有2个。
public List<Integer> majorityElement(int[] nums) {
List<Integer> rt = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
return rt;
}
int m1 = nums[0];
int m2 = 0;
int c1 = 1;
int c2 = 0;
for (int i = 1; i < nums.length; i++) {
int x = nums[i];
if (x == m1) {
c1++;
} else if (x == m2) {
c2++;
} else if (c1 == 0) {
m1 = x;
c1 = 1;
} else if (c2 == 0) {
m2 = x;
c2 = 1;
} else {
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for (int i = 0; i < nums.length; i++) {
if (m1 == nums[i]) {
c1++;
} else if (m2 == nums[i]) {
c2++;
}
}
if (c1 > nums.length / 3) {
rt.add(m1);
}
if (c2 > nums.length / 3) {
rt.add(m2);
}
return rt;
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)