[LeetCode][JavaScript]Majority Element II

Majority Element II

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.

https://leetcode.com/problems/majority-element-ii/

 

 


 

 

Moore voting algorithm,时间复杂度是O(3n),空间复杂度是O(1)。

第一轮遍历,每找到三个不同的数,就删掉这三个数,最后剩下的就是可能的结果。

为什么是可能的结果呢,比如:

majorityElement([1,2,2,3,3,3,3,3]) 遍历会删掉[1,2,3],最后剩下2(count == 1)和3(count == 4),但明显只有3才是正确答案。

所以还需要两轮遍历,确定结果。

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[]}
 4  */
 5 var majorityElement = function(nums) {
 6     var i = 0, res = null, trinity = [], curr = null; 
 7     var result = [];
 8     for(i = 0; i < nums.length; i++){
 9         curr = nums[i];
10         res = isInTrinity(curr, trinity);
11         if(res !== -1){
12             trinity[res].count++;
13         }else{
14             if(trinity.length <= 1){
15                 trinity.push({key : curr, count : 1});
16             }else{
17                 trinity[1].count--;
18                 if(trinity[1].count === 0){
19                     trinity.pop();
20                 }
21                 trinity[0].count--;
22                 if(trinity[0].count === 0){
23                     trinity.shift();
24                 }
25             }
26         }
27     }    
28     if(trinity[0]){
29         verifyNum(trinity[0].key, result);
30     }
31     if(trinity[1]){
32         verifyNum(trinity[1].key, result);
33     }
34     return result;
35     
36     function verifyNum(num, result){
37         var count = 0;
38         for(i = 0; i < nums.length; i++){
39             if(nums[i] === num){
40                 count++;
41             }
42         }
43         if(count > nums.length / 3){
44             result.push(num);
45         }
46     }
47     function isInTrinity(num, trinity){
48         for(var i = 0; i < trinity.length; i++){
49             if(trinity[i].key === num){
50                 return i;
51             }
52         }
53         return -1;
54     }
55 };

 

 

 

 
 
 
posted @ 2015-06-29 17:53  `Liok  阅读(372)  评论(0编辑  收藏  举报