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

LintCode-Majority Number

时间:2014-12-28 00:19:54      阅读:179      评论: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

For [1, 1, 1, 1, 2, 2, 2], return 1

Challenge

O(n) time and O(1) space

Solution:

 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         if (nums==null || nums.size()==0) return -1;
 8         int len = nums.size();
 9 
10         int cur = nums.get(0);
11         int count = 1;
12         for (int i=1;i<len;i++){
13             if (cur!=nums.get(i)){
14                 count--;
15                 if (count==0){
16                     cur = nums.get(i);
17                     count=1;
18                 }
19             } else {
20                 count++;
21             }
22         }
23 
24         return cur;
25     }
26 }

 

LintCode-Majority Number

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4189349.html

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