zoukankan      html  css  js  c++  java
  • 229. 求众数 II-数组/众数-中等

    问题描述

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

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

    示例 1:

    输入:[3,2,3]
    输出:[3]
    示例 2:

    输入:nums = [1]
    输出:[1]
    示例 3:

    输入:[1,1,1,3,3,2,2,2]
    输出:[1,2]
     

    提示:

    1 <= nums.length <= 5 * 104
    -109 <= nums[i] <= 109

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/majority-element-ii

    解答

    //投票法plus
    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            int n = nums.length;
            List<Integer> res = new ArrayList<>();
            if(n == 0)return res;
            int cand1 = 0, cand2 = 0, c1 = 0, c2 = 0;
            for(int i:nums){
                if(c1 == 0){
                    if(c2 != 0 && cand2 == i){
                        c2++;
                        continue;
                    }else{
                        cand1 = i;
                        c1++;
                        continue;
                    }
                }
                if(cand1 == i){
                    c1++;
                    continue;
                }
                if(c2 == 0){
                    cand2 = i;
                    c2++;
                    continue;
                }
                if(cand2 == i){
                    c2++;
                    continue;
                }
    
                c1--;
                c2--;
            }
            int min = n/3, num1 = 0, num2 = 0;
            for(int i:nums){
                if(cand1 == i)num1++;
                else if(cand2 == i)num2++;
            }
    
            if(num1>min)res.add(cand1);
            if(num2>min)res.add(cand2);
            return res;
        }
    }
  • 相关阅读:
    python学习笔记
    win10优化设置
    jpa基本用法
    5_方法(函数)、参数传递
    12_文件基本权限
    10_管理用户和组
    9_用户和组的相关配置文件
    7_vim 编辑器使用技巧
    8_Xmanager 远程连接 Linux 系统工具使用方法
    5_Linux系统目录结构,相对/绝对路径
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13814157.html
Copyright © 2011-2022 走看看