Advertisement
sweet1cris

Untitled

Jan 9th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums: A list of integers
  4.      * @return: The majority number that occurs more than 1/3
  5.      */
  6.     public int majorityNumber(ArrayList<Integer> nums) {
  7.         int candidate1 = 0, candidate2 = 0;
  8.         int count1, count2;
  9.         count1 = count2 = 0;
  10.         for (int i = 0; i < nums.size(); i++) {
  11.             if (candidate1 == nums.get(i)) {
  12.                 count1 ++;
  13.             } else if (candidate2 == nums.get(i)) {
  14.                 count2 ++;
  15.             } else if (count1 == 0) {
  16.                 candidate1 = nums.get(i);
  17.                 count1 = 1;
  18.             } else if (count2 == 0) {
  19.                 candidate2 = nums.get(i);
  20.                 count2 = 1;
  21.             } else {
  22.                 count1--;
  23.                 count2--;
  24.             }
  25.         }
  26.         count1 = count2 = 0;
  27.         for (int i = 0; i < nums.size(); i++) {
  28.             if (nums.get(i) == candidate1) {
  29.                 count1++;
  30.             } else if (nums.get(i) == candidate2) {
  31.                 count2++;
  32.             }
  33.         }    
  34.         return count1 > count2 ? candidate1 : candidate2;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement