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;
        }
    }
  • 相关阅读:
    (一)python 简单网页爬虫
    环形队列的应用
    AutoResetEvent 和 ManualResetEvent 多线程应用
    委托 和 事件
    Action 和 Func 的用法以及区别
    IIS 配置缓存
    IIS 发布双证书
    函数中返回局部变量的问题
    python函数2-函数参数
    Python基础语法6-冒泡排序
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13712884.html
Copyright © 2011-2022 走看看