zoukankan      html  css  js  c++  java
  • Majority Element II——LeetCode

    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.

    题目大意:给定一个大小为n的数组,找出Majority元素,满足出现次数大于 ⌊ n/3 ⌋ 次。

    解题思路:大于 ⌊ n/3 ⌋ 次,那么应该最多有两个Majority元素,之前有道题是找出 大于⌊ n/2 ⌋ 次Majority元素,这道题有点类似,稍微复杂一点,还是利用投票算法,count作为对元素的计数,候选元素等于当前元素则count+1,否则减1,count等于0则更换候选元素。

        public List<Integer> majorityElement(int[] nums) {
            List<Integer> res = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return res;
            }
            int can1 = nums[0], can2 = nums[0], cnt1 = 1, cnt2 = 0;
            for (int i = 1; i < nums.length; i++) {
                int num = nums[i];
                if ((cnt1 == 0 && num != can2)) {
                    can1 = num;
                } else if (cnt2 == 0 && num != can1) {
                    can2 = num;
                }
                if (num == can1) {
                    cnt1++;
                } else if (num == can2) {
                    cnt2++;
                } else {
                    cnt1--;
                    cnt2--;
                }
                cnt1 = cnt1 < 0 ? 0 : cnt1;
                cnt2 = cnt2 < 0 ? 0 : cnt2;
            }
            cnt1 = 0;
            cnt2 = 0;
            for (int num : nums) {
                if (num == can1) {
                    cnt1++;
                } else if (num == can2) {
                    cnt2++;
                }
            }
            if (cnt1 > nums.length / 3)
                res.add(can1);
            if (cnt2 > nums.length / 3)
                res.add(can2);
            return res;
        }
  • 相关阅读:
    时间日期总览
    Mysql一次更新多条数据
    windows远程桌面连接无法粘贴
    vmware workstation pro密钥
    C#自动生成XML文件
    Mysql 缺少MSVCR120DLL问题
    hdu 5672 Strings 模拟
    poj 1328 雷达覆盖 贪心
    hdu 5667 Sequence (矩阵快速幂)
    CodeForces 652D Nested Segments 树状数组
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4609251.html
Copyright © 2011-2022 走看看