229. Majority Element II

来源:互联网 发布:那种牌子的网络电视好 编辑:程序博客网 时间:2024/06/05 07:39

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.

思路: 跟majority element一样,还是投票法,因为求个数大于n/3的数字,我们知道最多只有两个。

设置一个 num1=0 和count1=0

num2=0和count2=0

如果 nums[i]==num1 count1++

如果 nums[i]=num2 count2++;

如果都不等的话,如果count1==0 num1=nums[i]

如果count2==0 num2=nums[i],

如果count1和count2都不等于0的话,count1--,count2--;

循环结束之后,判断num1出现的次数是不是大于n/3,num2出现的次数是不是大于n/3;

代码如下(已通过leetcode)

public class Solution {
   public List<Integer> majorityElement(int[] nums) {
    List<Integer> list=new ArrayList<Integer>();
    if(nums==null||nums.length==0) return list;
    int num1=Integer.MIN_VALUE;
    int num2=Integer.MIN_VALUE;
    int count1=0;
    int count2=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++;
    } else {
    if(count2==0) {
    num2=nums[i];
    count2++;
    } else {
    count1--;
    count2--;
    }
    }
    }
    }
    //System.out.println("num1: "+num1+" "+"count1 "+count1+"\t"+"num2: "+num2+" "+"count2 "+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(count1>nums.length/3) list.add(num1);
    if(count2>nums.length/3) list.add(num2);
    return list;
   }
}

0 0
原创粉丝点击