Missing a test case


  • 0
    J

    The following code is accepted by OJ, however it is wrong given test case [4,2,2,1,1]. The reason is nums[0] is counted twice.

    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            List<Integer> res = new ArrayList<>();
            if (nums == null || nums.length == 0) return res;
            
            int v1 = nums[0], v2 = 0, c1 = 1, c2 = 0;
            for (int v : nums)
                if (v == v1) c1 ++;
                else if (v == v2) c2 ++;
                else if (c1 == 0) { c1 = 1; v1 = v; }
                else if (c2 == 0) { c2 = 1; v2 = v; }
                else { c1 --; c2 --; }
    
            c1 = c2 = 0;
            for (int v : nums)
                if (v == v1) c1 ++;
                else if (v == v2) c2 ++;
            if (c1 > nums.length/3) res.add(v1);
            if (c2 > nums.length/3) res.add(v2);
            
            return res;
        }
    }

  • 0
    P

    Can this be avoided by starting looping v from 1 ?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.