[Lintcode]Majority Number

来源:互联网 发布:tp3.2数据库配置 编辑:程序博客网 时间:2024/04/28 02:30

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

要求:O(n) time and O(1) extra space

投票算法, 一般需要再遍历一遍,为防止不存在majority number的情况发生。

public class Solution {    /**     * @param nums: a list of integers     * @return: find a  majority number     */    public int majorityNumber(ArrayList<Integer> nums) {                if(nums.size() == 0) return -1;        int res = 0;        int tmp = 0;        for(Integer i : nums) {            if(res == 0) {                tmp = i;            }            if(i == tmp) {                res ++;            }            else {                res--;            }        }                return tmp;    }}


0 0
原创粉丝点击