package com.app.main.LeetCode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 229
*
* medium
*
* https://leetcode.com/problems/majority-element-ii/
*
* Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
*
* Note: The algorithm should run in linear time and in O(1) space.
*
* Example 1:
*
* Input: [3,2,3]
* Output: [3]
* Example 2:
*
* Input: [1,1,1,3,3,2,2,2]
* Output: [1,2]
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/10/1
* Time:下午11:35
*/
public class MajorityElementII {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
if (map.get(nums[i]) > nums.length / 3 ) {
if (!result.contains(nums[i])) {
result.add(nums[i]);
}
}
} else {
map.put(nums[i], 1);
if (!result.contains(nums[i]) && map.get(nums[i]) > nums.length / 3) {
result.add(nums[i]);
}
}
}
return result;
}
// 一个关键点, 1 / 3 次 =》 最多有两个解
public List<Integer> majorityElement2(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums.length == 0)
return res;
int num1 = nums[0]; int num2 = nums[0]; int count1 = 1; int count2 = 0 ;
for (int val : nums) {
if(val == num1)
count1++;
else if (val == num2)
count2++;
else if (count1 == 0) {
num1 = val;
count1++;
}
else if (count2 == 0) {
num2 = val;
count2++;
}
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for(int val : nums) {
if(val == num1)
count1++;
else if(val == num2)
count2++;
}
if(count1 > nums.length/3)
res.add(num1);
if(count2 > nums.length/3)
res.add(num2);
return res;
}
}