【LeetCode】229. Majority Element II 求众数 II(Medium)(JAVA)

【LeetCode】229. Majority Element II 求众数 II(Medium)(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.

Follow-up: Could you solve the problem in linear time and in O(1) space?

Example 1:

Input: nums = [3,2,3]
Output: [3]

Example 2:

Input: nums = [1]
Output: [1]

Example 3:

Input: nums = [1,2]
Output: [1,2]

Constraints:

  • 1 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

题目大意

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

解题方法

  1. 暴力的解法就是用一个 Map 把出现的 num 和对应的次数存起来,遇到超过 n / 3 次的元素就存进结果,时间复杂度为 O(n),但是空间复杂度为 O(n),不符合空间复杂度为 O(1) 的要求
  2. 因为超过 n / 3 次的元素最多两个,所以用两个元素来表示可能超过 n / 3 出现次数的元素,后续如果是这两个元素就次数 +1, 如果不是就都 -1
  3. 最后再通过一次遍历,判断最后这两个中的元素是否是超过了 n / 3,因为可能不存在超过 n / 3 的元素
  4. note: 为什么可能是元素都需要 -1 呢?这样不是减了两次了吗?因为所有元素不相等的时候,表示所有的 count 都是大于等于 1,如果有一个元素等于 0 这次就不会有 - 1 操作了,后续要减的时候都要补上
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> list = new ArrayList<>();
        if (nums.length == 0) return list;
        if (nums.length == 1) {
            list.add(nums[0]);
            return list;
        }
        int[] count = new int[2];
        int[] arr = new int[2];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
            boolean flag = false;
            for (int j = 0; j < arr.length && !flag; j++) {
                if (arr[j] == nums[i]) {
                    flag = true;
                    count[j]++;
                }
            }
            for (int j = 0; j < arr.length && !flag; j++) {
                if (count[j] == 0) {
                    flag = true;
                    count[j]++;
                    arr[j] = nums[i];
                }
            }
            if (!flag) {
                for (int j = 0; j < count.length; j++) {
                    count[j]--;
                }
            }
        }
        for (int i = 0; i < count.length; i++) {
            count[i] = 0;
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] == nums[i]) {
                    count[j]++;
                    break;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            if (count[i] > nums.length / 3) list.add(arr[i]);
        }
        return list;
    }
}

执行耗时:2 ms,击败了96.27% 的Java用户
内存消耗:42.5 MB,击败了54.62% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值