zoukankan      html  css  js  c++  java
  • LeetCode(229):Majority Element ||

    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.

    题意:找出给定数组中出现次数多于数组长度三分之一的元素

    思路:根据提示,可知这样的元素最多只能存在两个,因此根据摩尔投票法可以进行求解。

    代码:

    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
             int cnt1=0, cnt2 =0;
             int a=-1,b=-1;
             for(int n:nums){
                 if(n==a) cnt1++;
                 else if(n==b) cnt2++;
                 else if(cnt1==0){
                     a= n;
                     cnt1=1;
                 }else if(cnt2==0){
                     b = n ;
                     cnt2 = 1;
                 }else{
                     cnt1--;
                     cnt2--;
                 }
             }
             cnt1 = 0;
             cnt2 = 0;
             for(int n:nums){
                 if(n==a) cnt1++;
                 else if(n==b) cnt2++;
             }
             List<Integer> result=new ArrayList<Integer>();
             if(cnt1 > nums.length/3) result.add(a);
             if(cnt2 > nums.length/3) result.add(b);
             return result;
        }
    }
  • 相关阅读:
    2021广东省强网杯WriteUp
    2021 数字四川创新大赛WriteUp
    2021 陇剑杯wp
    2021 羊城杯WriteUP
    如何翻安全四大顶会的文章
    2021 祥云杯 wp
    codeql初探
    sqlmap应用
    sql注入2
    sql注入
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5200861.html
Copyright © 2011-2022 走看看