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

LintCode-Majority Number II

时间:2014-12-28 00:28:38      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.

Find it.

Note

There is only one majority number in the array

Example

For [1, 2, 1, 2, 1, 3, 3] 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: The majority number that occurs more than 1/3
 5      */
 6     public int majorityNumber(ArrayList<Integer> nums) {
 7         if (nums.size()==0) return -1;
 8         if (nums.size()<3) return nums.get(0);
 9         int len = nums.size();
10 
11         int n1 = nums.get(0), n2 = 0;
12         int count1 = 1, count2 = 0;
13 
14         for (int i=1;i<len;i++)
15             if (nums.get(i)==n1)
16                 count1++;
17             else if (nums.get(i)==n2)
18                 count2++;
19             else {
20                 if (count1==0) {
21                     n1 = nums.get(i);
22                     count1 = 1;
23                 } else if (count2==0){
24                     n2 = nums.get(i);
25                     count2 = 1;
26                 } else {
27                     count1--;
28                     count2--;
29                 }
30             }
31 
32         if (count1!=0 && count2!=0){
33             count1 = 0;
34             count2 = 0;
35             for (int i=0; i<len;i++)
36                 if (nums.get(i)==n1) count1++;
37                 else if (nums.get(i)==n2) count2++;
38             if (count1>len/3) return n1;
39             else return n2;
40         } else if (count1!=0) return n1;
41         else return n2;
42                 
43     }
44 }

 

LintCode-Majority Number II

标签:

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

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