Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
80 lines (69 loc) · 1.83 KB

File metadata and controls

80 lines (69 loc) · 1.83 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
if (nums.length == 0) {
return result;
}
if (nums.length <= 2) {
result.add(nums[0]);
if (nums.length == 2 && nums[0] != nums[1]) {
result.add(nums[1]);
}
return result;
}
int n1 = nums[0];
int c1 = 1;
int twoIdx = 1;
while (twoIdx < nums.length) {
if (nums[twoIdx] != n1) {
break;
} else {
c1 += 1;
twoIdx += 1;
}
}
if (twoIdx == nums.length) {
result.add(n1);
return result;
}
int n2 = nums[twoIdx];
int c2 = 1;
for (int i = twoIdx+1; i < nums.length; i++) {
if (n1 == nums[i]) {
c1 += 1;
} else if (n2 == nums[i]) {
c2 += 1;
} else if (c1 == 0) {
c1 = 1;
n1 = nums[i];
} else if (c2 == 0) {
c2 = 1;
n2 = nums[i];
} else {
c1 -= 1;
c2 -= 1;
}
}
int count1 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == n1) {
count1 += 1;
}
}
if (count1 > nums.length / 3) {
result.add(n1);
}
if (n1 != n2) {
int count2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == n2) {
count2 += 1;
}
}
if (count2 > nums.length / 3) {
result.add(n2);
}
}
return result;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.