Majority Number

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

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

 1 public class Solution {
 2     /**
 3      * @param nums: a list of integers
 4      * @return: find a  majority number
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         int count = 0, candidate = -1;
 8         for (int i = 0; i < nums.size(); i++) {
 9             if (count == 0) {
10                 candidate = nums.get(i);
11                 count = 1;
12             } else if (candidate == nums.get(i)) {
13                 count++;
14             } else {
15                 count--;
16             }
17         }
18         return candidate;
19     }
20 }

 

posted @ 2016-04-02 09:09  YuriFLAG  阅读(132)  评论(0)    收藏  举报