[刷题]Majority Number II

来源:互联网 发布:开源三网合一源码 编辑:程序博客网 时间:2024/05/01 18:02

[LintCode]Majority Number II

public class Solution {    /**     * @param nums: A list of integers     * @return: The majority number that occurs more than 1/3     */    public int majorityNumber(ArrayList<Integer> nums) {        // 2015-09-07        if (nums == null || nums.size() == 0) {            return -1;        }        int candidate1 = 0;        int candidate2 = 0;        int count1 = 0;        int count2 = 0;        for (int i = 0; i < nums.size(); i++) {            // 注意if的顺序,确保candidate1和candidate2不是同一个数            if (count1 == 0) {                candidate1 = nums.get(i);                count1++;            } else if (candidate1 == nums.get(i)) {                count1++;            } else if (count2 == 0) {                candidate2 = nums.get(i);                count2++;            } else if (candidate2 == nums.get(i)) {                count2++;            } else {                count1--;                count2--;            }        }                // 此时只剩下两个数,candidate1和candidate2        count1 = 0;        count2 = 0;        for (int i = 0; i < nums.size(); i++) {            if (candidate1 == nums.get(i)) {                count1++;            }            if (candidate2 == nums.get(i)) {                count2++;            }        }        return count1 > count2 ? candidate1 : candidate2;    }}


0 0