LeetCode 229. Majority Element II

本文详细解析了 LeetCode 中一道关于寻找数组中出现次数超过 n/3 的元素的问题,提供了一种线性时间和 O(1) 空间的解决方案,并附带 Java 代码实现。

原题链接在这里:https://leetcode.com/problems/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.

题解:

类似Majority Element I的method 3. 因为个数超过n/3的值最多有两个,现在改成维护两个最常出现的值。

最后再扫一遍数组,查看这两个最常出现值的实际出现次数,看看是否大于n/3, 大于的都加入返回res中.

Note: 两个参选major1, major2不能相等. 比如都猜1, 数组只有一个1. 那么走第二遍时两个的count都超过了总长的1/3, 1就会加两遍.

Time Complexity: O(n), 一共扫了两遍数组. Space O(1).

AC Java:

 1 class Solution {
 2     public List<Integer> majorityElement(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         //最多有两个数字大于n/3
 9         int major1 = 1;
10         int major2 = 2;
11         int count1 = 0;
12         int count2 = 0;
13         for(int i = 0; i<nums.length; i++){
14             if(nums[i] == major1){
15                 count1++;
16             }else if(nums[i] == major2){
17                 count2++;
18             }else if(count1 == 0){
19                 major1 = nums[i];
20                 count1 = 1;
21             }else if(count2 == 0){
22                 major2 = nums[i];
23                 count2 = 1;
24             }else{
25                 count1--;
26                 count2--;
27             }
28         }
29         
30         count1 = 0;
31         count2 = 0;
32         for(int num : nums){
33             if(num == major1){
34                 count1++;
35             }
36             if(num == major2){
37                 count2++;
38             }
39         }
40         
41         if(count1 > nums.length/3){
42             res.add(major1);
43         }
44         if(count2 > nums.length/3){
45             res.add(major2);
46         }
47         return res;
48     }
49 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6268085.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值