首页 > 其他 > 详细

lintcode-easy-Majority Number

时间:2016-02-26 08:08:33      阅读:156      评论:0      收藏:0      [点我收藏+]

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

Challenge

O(n) time and O(1) extra space

 

投票法,利用一下要找的这个数大于size的一半这个性质

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        if(nums == null || nums.size() == 0)
            return 0;
        
        Integer result = null;
        int count = 0;
        
        for(int i = 0; i < nums.size(); i++){
            if(result == null){
                result = nums.get(i);
                count = 1;
            }
            else if(nums.get(i) == result){
                count++;
            }
            else{
                count--;
                if(count == 0){
                    result = nums.get(i);
                    count = 1;
                }
            }
        }
        
        return result;
    }
}

 

lintcode-easy-Majority Number

原文:http://www.cnblogs.com/goblinengineer/p/5219161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!