lintcode--主元素

来源:互联网 发布:ubuntu emacs 编辑:程序博客网 时间:2024/09/21 06:36

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。


 注意事项

You may assume that the array is non-empty and the majority number always exist in the array.

样例

给出数组[1,1,1,1,2,2,2],返回 1






public class Solution {
    /**
     * 第二种方法 时间复杂度为O(n),空间复杂度为O(1)  
        //因为主元素个数至少大于等于数组元素的一般  
        //所以先nums[0]赋值给temp,再遍历数组,若等于temp,则n++,否则n--,
            当n=0时交换temp的值并把n置1。  
        //最后的temp就是主元素。  
     */
    public int majorityNumber(ArrayList<Integer> nums){
        int n = 1;//计数
        int temp = nums.get(0);//先赋值给date,
        for(int i =1;i<nums.size();i++){//再遍历数组
           
           if(temp == nums.get(i)){//若等于temp,则n++,
                n++;
            }else{
                n--;//不相同否则--
            }
            if(n == 0){//当n=0时交换temp的值并把n置1。  
                temp = nums.get(i);//
                n =1;
            }
        }
        return temp;//当n不为0的时候的数
    }
}