Majority Number I
Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
Challenge
O(n) time and O(1) extra space
public int majorityNumber(List<Integer> nums) { int candidate = 0, count = 0; for(int num : nums) { if(num == candidate) { count++; } else if(count != 0) { count--; } else { candidate = num; count = 1; } } return candidate; }
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.
Example
Given [1, 2, 1, 2, 1, 3, 3]
, return 1
.
public List<Integer> majorityElement(int[] nums) { int cnt1=0, cnt2=0; int a = 0, b = 0; for(int n: nums){ if (cnt1 == 0 || n == a) { cnt1++; a = n; } else if (cnt2 == 0 || n==b) { cnt2++; b = n; } else { cnt1--; cnt2--; } } cnt1 = cnt2 = 0; for(int n: nums){ if (n==a) cnt1++; else if (n==b) cnt2++; } List<Integer> result = new ArrayList<>(); if (cnt1 > nums.length/3) result.add(a); if (cnt2 > nums.length/3) result.add(b); return result; }
Majority Number III
Given an array of integers and a number k, the majority number is the number that occurs more than 1/k
of the size of the array. Find it.
Example
Given [3,1,2,3,2,3,3,4,4,4]
and k=3
, return 3
.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(k) extra space
public int majorityNumber(List<Integer> nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for(int num:nums) { if(map.containsKey(num)) { map.put(num, map.get(num)+1); } else { if(map.size() == k-1) { List<Integer> trash = new ArrayList<>(); for(int key:map.keySet()) { int cnt = map.get(key); if(--cnt == 0) { trash.add(key); } else { map.put(key, cnt); } } for(int key:trash) map.remove(key); } else { map.put(num, 1); } } } for(int key:map.keySet()) { int cnt = 0; for(int num:nums) { if(num==key) cnt++; } if(cnt > nums.size()/k) return key; } return -1; }
C++的代码:
vector<int> majorityElement(vector<int>& nums) { unordered_map<int,int> map; for(int num:nums) { if(map.size() < 2 || map.count(num)) { map[num]++; } else { vector<int> keys; for(auto& p:map) { if(--p.second == 0) { keys.push_back(p.first); } } for(int key:keys) map.erase(key); } } vector<int> result; for(auto& p : map) { int cnt = 0; for(int num:nums) { if(num == p.first && ++cnt > nums.size()/3) { result.push_back(num); break; } } } return result; }
Reference: