lintcode-medium-Majority Number II
Given an array of integers, the majority number is the number that occursmore than 1/3
of the size of the array.
Find it.
Notice
There is only one majority number in the array.
Example
Given [1, 2, 1, 2, 1, 3, 3]
, return 1
.
Challenge
O(n) time and O(1) extra space.
public class Solution { /** * @param nums: A list of integers * @return: The majority number that occurs more than 1/3 */ public int majorityNumber(ArrayList<Integer> nums) { // write your code if(nums == null || nums.size() == 0) return 0; Integer num1 = null; Integer num2 = null; int count1 = 0; int count2 = 0; for(int i = 0; i < nums.size(); i++){ int temp = nums.get(i); if(num1 == null){ num1 = temp; count1 = 1; } else if(num1 == temp){ count1++; } else if(num2 == null){ num2 = temp; count2 = 1; } else if(num2 == temp){ count2++; } else{ count1--; count2--; if(count1 == 0){ num1 = temp; count1 = 1; } if(count2 == 0){ num2 = temp; count2 = 1; } } } count1 = 0; count2 = 0; for(int i = 0; i < nums.size(); i++){ if(num1 == nums.get(i)) count1++; if(num2 == nums.get(i)) count2++; } if(count1 > nums.size() / 3) return num1; return num2; } }