zoukankan      html  css  js  c++  java
  • 229. Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

    Note: The algorithm should run in linear time and in O(1) space.

    Example 1:

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

    Example 2:

    Input: [1,1,1,3,3,2,2,2]
    Output: [1,2]

    there're at most 2 candidates, use voting algorithm
    use two counters for two candidates

    time = O(n), space = O(1)

    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            if(nums == null || nums.length == 0) {
                return new ArrayList<>();
            }
            int number1 = nums[0], counter1 = 0;
            int number2 = nums[0], counter2 = 0;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] == number1) {
                    counter1++;
                } else if(nums[i] == number2) {
                    counter2++;
                } else if(counter1 == 0) {
                    counter1++;
                    number1 = nums[i];
                } else if(counter2 == 0) {
                    counter2++;
                    number2 = nums[i];
                } else {
                    counter1--;
                    counter2--;
                }
            }
            
            counter1 = 0; counter2 = 0;
            for(int x : nums) {
                if(x == number1) {
                    counter1++;
                } else if(x == number2) {
                    counter2++;
                }
            }
            
            List<Integer> res = new ArrayList<>();
            if(counter1 > nums.length / 3) {
                res.add(number1);
            }
            if(counter2 > nums.length / 3) {
                res.add(number2);
            }
            return res;
        }
    }
  • 相关阅读:
    SVN操作指南
    .NET Tools
    SQL条件查询控件
    txt文件导入Sql Server数据库表方法
    黑盒测试用例设计方法
    JS库
    在 C# 中 ("x" == "X") 何时成立?
    奶牛问题,别人写的,自己试了一下.
    Some Cool Tips For .NET
    Excel Data Reader Read Excel files in .NET
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13712884.html
Copyright © 2011-2022 走看看