Skip to content

Commit c434331

Browse files
committed
add major ele ii
1 parent c40c5b5 commit c434331

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

majority-element-ii/README.md

Whitespace-only changes.

majority-element-ii/Solution.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
public class Solution {
2+
public List<Integer> majorityElement(int[] nums) {
3+
if(nums.length == 0) return Collections.emptyList();
4+
5+
int n1 = nums[0];
6+
int n2 = nums[0];
7+
8+
int c1 = 0;
9+
int c2 = 0;
10+
11+
for(int i = 0; i < nums.length; i++){
12+
13+
// put to an empty slot
14+
if(c1 <= 0 && nums[i] != n2){
15+
n1 = nums[i];
16+
c1 = 1;
17+
continue;
18+
}
19+
20+
if(c2 <= 0 && nums[i] != n1){
21+
n2 = nums[i];
22+
c2 = 1;
23+
continue;
24+
}
25+
26+
// add count
27+
if(nums[i] == n1){
28+
c1++;
29+
continue;
30+
}
31+
32+
if(nums[i] == n2){
33+
c2++;
34+
continue;
35+
}
36+
37+
// no match
38+
39+
c1--;
40+
c2--;
41+
}
42+
43+
// faint
44+
return new ArrayList<>(IntStream.of(n1, n2)
45+
.filter(n ->
46+
Arrays.stream(nums).filter(i -> n == i).count() > nums.length / 3)
47+
.boxed()
48+
.collect(Collectors.toSet()));
49+
}
50+
}

majority-element-ii/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Majority Element II
4+
date: 2015-06-29 13:42:29+08:00
5+
leetcode_id: 229
6+
---
7+
{% include_relative README.md %}

0 commit comments

Comments
 (0)