首页 > 其他 > 详细

LintCode-Majority Number

时间:2014-12-28 00:16:47      阅读:403      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!