@@ -0,0 +1,1557 @@
+package com.freetymekiyan.algorithms.level.medium;%0A%0Aimport java.util.Collections;%0Aimport java.util.List;%0A%0A/**%0A * Given an integer array of size n, find all elements that appear more than %E2%8C%8A n/3 %E2%8C%8B times. The algorithm should run in%0A * linear time and in O(1) space.%0A * %3Cp%3E%0A * Hint:%0A * %3Cp%3E%0A * How many majority elements could it possibly have?%0A * %3Cp%3E%0A * Tags: Array%0A * Similar Problems: (E) Majority Element%0A */%0Apublic class MajorityElement2 %7B%0A%0A    public List%3CInteger%3E majorityElement(int%5B%5D nums) %7B%0A        if (nums == null %7C%7C nums.length == 0) %7B%0A            return Collections.EMPTY_LIST;%0A        %7D%0A        int num1 = 0;%0A        int count1 = 0;%0A        int num2 = 0;%0A        int count2 = 0;%0A        List%3CInteger%3E res = new ArrayList%3C%3E();%0A        for (int n : nums) %7B%0A            if (n == num1) %7B%0A                count1++;%0A            %7D else if (n == num2) %7B%0A                count2++;%0A            %7D else if (count1 == 0) %7B%0A                num1 = n;%0A                count1 = 1;%0A            %7D else if (count2 == 0) %7B%0A                num2 = n;%0A                count2 = 1;%0A            %7D else %7B%0A                count1--;%0A                count2--;%0A            %7D%0A        %7D%0A        count1 = 0;%0A        count2 = 0;%0A        for (int n : nums) %7B%0A            if (n == num1) %7B%0A                count1++;%0A            %7D else if (n == num2) %7B%0A                count2++;%0A            %7D%0A        %7D%0A        if (count1 %3E nums.length / 3) %7B%0A            res.add(num1);%0A        %7D%0A        if (count2 %3E nums.length / 3) %7B%0A            res.add(num2);%0A        %7D%0A        return res;%0A    %7D%0A%0A%7D%0A

add Majority Element 2