这是两道数组中找元素的题目,229是169的进阶版。先看169。
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
题目已经说明可以认为数组非空且出现次数大于数组元素个数一半的元素必定存在。想象一下,假设有n种不同颜色的小球,其中一种颜色的数量超过了总数的一半,那么我们把这些小球按颜色排序后,取最中间的小球,颜色一定是超过总数一半的那个颜色。所以这题可以排序,取中间值,AC码如下:
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[(int)nums.length/2];
}
229题目如下:
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.
这道题目中就没有任何的假设了,要判断数组为空等等特殊情况。一组数中要出现次数大于1/3的数字至多只能有两个,因此我们可以先遍历一遍数组,求出出现次数最多的两个元素,之后再次遍历数组,统计这两个数字出现的次数,最后判断是否大于数组长度的1/3。符合条件则加入result集,AC码如下:
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
if(nums==null||nums.length==0)return result;
int count1=0,count2=0,num1=nums[0],num2=nums[0];
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=1;
}else if(count2==0){
num2=nums[i];
count2++;
}else{
count1--;
count2--;
}
}
count1=0;
count2=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==num1){
count1++;
}else if(nums[i]==num2){
count2++;
}
}
if(nums.length/3<count1){
result.add(num1);
}
if(nums.length/3<count2){
result.add(num2);
}
return result;
}