@@ -45,13 +45,35 @@ Boyer–Moore majority vote algorithm
4545### ** Python3**  
4646
4747``` python 
48- 48+ class  Solution :
49+  def  majorityElement (self nums : List[int ]) -> int :
50+  cnt =  major =  0 
51+  for  num in  nums:
52+  if  cnt ==  0 :
53+  major =  num
54+  cnt =  1 
55+  else :
56+  cnt +=  (1  if  major ==  num else  - 1 )
57+  return  major
4958``` 
5059
5160### ** Java**  
5261
5362``` java 
54- 63+ class  Solution  {
64+  public  int  majorityElement (int [] nums ) {
65+  int  cnt =  0 , major =  0 ;
66+  for  (int  num :  nums) {
67+  if  (cnt ==  0 ) {
68+  major =  num;
69+  cnt =  1 ;
70+  } else  {
71+  cnt +=  (major ==  num ?  1  :  - 1 );
72+  }
73+  }
74+  return  major;
75+  }
76+ }
5577``` 
5678
5779### ** JavaScript**  
@@ -62,23 +84,63 @@ Boyer–Moore majority vote algorithm
6284 * @return  {number}  
6385 */  
6486var  majorityElement  =  function (nums ) {
65-  let  candidate =  0 , count =  0 ;
66-  for  (let  num of  nums) {
67-  if  (count ==  0 ) candidate =  num;
68-  if  (candidate ==  num) {
69-  count++ ;
87+  let  cnt =  0 ;
88+  let  major =  0 ;
89+  for  (const  num  of  nums) {
90+  if  (cnt ==  0 ) {
91+  major =  num;
92+  cnt =  1 ;
7093 } else  {
71-  count -- ;
94+  cnt  +=  (major  ==  num  ? 1 : - 1 ) ;
7295 }
7396 }
74-  let  n =  0 ;
75-  for  (let  num of  nums) {
76-  if  (candidate ==  num) n++ ;
97+  return  major;
98+ };
99+ ``` 
100+ 101+ ### ** C++**  
102+ 103+ ``` cpp 
104+ class  Solution  {
105+ public:
106+  int majorityElement(vector<int >& nums) {
107+  int cnt = 0, major = 0;
108+  for (int num : nums) {
109+  if (cnt == 0) {
110+  major = num;
111+  cnt = 1;
112+  } else {
113+  cnt += (major == num ? 1 : -1);
114+  }
115+  }
116+  return major;
77117 }
78-  return  n >  (nums .length  /  2 ) ?  candidate :  - 1 ;
79118};
80119``` 
81120
121+ ### **C#** 
122+ 
123+ ```cs 
124+ public class Solution { 
125+  public int MajorityElement(int[] nums) { 
126+  int cnt = 0, major = 0; 
127+  foreach (int num in nums) 
128+  { 
129+  if (cnt == 0) 
130+  { 
131+  major = num; 
132+  cnt = 1; 
133+  } 
134+  else 
135+  { 
136+  cnt += (major == num ? 1 : -1); 
137+  } 
138+  } 
139+  return major; 
140+  } 
141+ } 
142+ ``` 
143+ 82144### ** ...**  
83145
84146``` 
0 commit comments