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

Majority Number

时间:2016-04-02 09:32:35      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Majority Number

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5346924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!