码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Majority Number

时间:2016-02-26 08:08:44      阅读:159      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!