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

[?]*Majority Element II

时间:2015-07-14 17:35:47      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

 

解题思路:

Majority Elements不同是这里需要维护两个变量n1和n2,如果下一个数与这两个数都不同的时候,count1和count2都减一,如果下一个数与n1或者n2相等的时候,对应的count++。最后的结果必定在n1或者n2中。

 

代码:

 1 public class Solution {
 2     public int majorityNumber(ArrayList<Integer> nums) {
 3         int n1 = nums.get(0), count1 = 1;
 4         int index = 1;
 5         for (; index < nums.size() && nums.get(index) == n1; index++) {
 6             count1++;
 7         }
 8         if (index == nums.size()) {
 9             return n1;
10         }
11         int n2 = nums.get(index), count2 = 1;
12         for (int i = index + 1; i < nums.size(); i++) {
13             if (nums.get(i) == n1) {
14                 count1++;
15             } else if (nums.get(i) == n2) {
16                 count2++;
17             } else {
18                 if (count1 == 0) {
19                     n1 = nums.get(i);
20                     count1 = 1;
21                 } else if (count2 == 0) {
22                     n2 = nums.get(i);
23                     count2 = 1;
24                 } else {
25                     count1--;
26                     count2--;
27                 }
28             }
29         }
30         if (count1 == 0) {
31             return n2;
32         } else if(count2 == 0) {
33             return n1;
34         } else {
35             int count = 0;
36             for (int n : nums) {
37                 if (n == n1) {
38                     count++;
39                 }
40             }
41             if (count > nums.size()/3) {
42                 return n1;
43             }
44             return n2;
45         }
46     }
47 }

 

reference:https://codesolutiony.wordpress.com/2015/03/15/lintcode-majority-element-ii/

[?]*Majority Element II

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4645611.html

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