【LeetCode】229.Majority Element II(Medium)解题报告
题目地址:https://leetcode.com/problems/majority-element-ii/#/description
题目描述:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Solutions:
public class Solution {
public List<Integer> majorityElement(int[] nums) {
int num1 = 0, num2 = 0; //num1和num2用来保存nums中的元素。
int count1 = 0, count2 = 0; //count1和count2分别保存num1和num2的个数。
List<Integer> list = new ArrayList<Integer>();
if(nums == null || nums.length == 0)
return list;
for(int i=0;i<nums.length;i++){
if(nums[i] == num1)
count1++;
else if(nums[i] == num2)
count2++;
else if(count1 == 0){
num1 = nums[i];
count1++;
}
else if(count2 == 0){
num2 = nums[i];
count2++;
}
else{
count1--;
count2--;
}
}
int check1 = 0, check2 = 0;
for(int i=0;i<nums.length;i++){
if(count1 !=0 && nums[i] == num1)
check1++;
if(count2!=0 && nums[i] == num2)
check2++;
}
if(check1 > nums.length/3)
list.add(num1);
if(check2 > nums.length/3)
list.add(num2);
return list;
}
}
另一个解法:
public class Solution {
public List<Integer> majorityElement(int[] nums) {
int n = nums.length, k = 3; //in this question, k=3 specifically
List<Integer> result = new ArrayList<Integer>();
if (n==0 || k<2) return result;
int[] candidates = new int[k-1];
int[] counts = new int[k-1];
for (int num: nums) {
boolean settled = false;
for (int i=0; i<k-1; i++) {
if (candidates[i]==num) {
counts[i]++;
settled = true;
break;
}
}
if (settled) continue;
for (int i=0; i<k-1; i++) {
if (counts[i]==0) {
counts[i] = 1;
candidates[i] = num;
settled = true;
break;
}
}
if (settled) continue;
for (int i=0; i<k-1; i++) counts[i] = (counts[i] > 0) ? (counts[i]-1) : 0;
}
Arrays.fill(counts, 0);
for (int num: nums) {
for (int i=0;i<k-1; i++) {
if (candidates[i]==num) {
counts[i]++;
break;
}
}
}
for (int i=0; i<k-1; i++) if (counts[i]>n/k) result.add(candidates[i]);
return result;
}
}
解题思路:
昨天刚做完找超过一半的那个数,今天变成了n/3,那么这样可以下去无数道题,前面n/2用的更多是一半的特殊性,我们最好找到一个通用的解法。其实对于这道题完全没有思路,这里我们注意到n/3的数不一定只有一个。解法一是一种通用的解法。对于之前的n/2,思路可以是将数组中的数两两一组(两个数不等),则最后余下的那个数可能是主数,如果题目说一定存在主数,那就不用检查了,如果不一定存在,则还需要检查一下。 对于本题,我们采用相同的思路,将三个不相等的数分为一组,则最后剩下的一个或两个可能为主数。我们再对其进行检查,找出真正的主数。进行返回。当然以后遇到四分之一,五分之一都不是什么问题了。对于解法二是LeetCode上面找到的解法,并没有理解,以后有时间再回来看吧。
Date:2017年6月4日