1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution { public List<Integer> majorityElement(int[] nums) { int candidate1 = 0; int candidate2 = 0; int votes1 = 0; int votes2 = 0;
for (int num : nums) { if (num == candidate1) { votes1++; continue; } if (num == candidate2) { votes2++; continue; }
if (votes1 == 0) { candidate1 = num; votes1++; continue; } if (votes2 == 0) { candidate2 = num; votes2++; continue; }
votes1--; votes2--; }
int count1 = 0; int count2 = 0;
for (int num : nums) { if (num == candidate1) { count1++; } else if (num == candidate2) { count2++; } }
List<Integer> list = new ArrayList<>(); if (count1 > nums.length / 3) { list.add(candidate1); } if (count2 > nums.length / 3) { list.add(candidate2); } return list; } }
|