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
    Python
    Python
    Django REST framework
    Django REST framework
    Django REST framework
    Django REST framework
    jquery.unobtrusive-ajax.js的扩展,做到片段式加载
    jquery.unobtrusive-ajax.js单独的用法
    不复杂的Autofac注入
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13712884.html
Copyright © 2011-2022 走看看