-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathmajority_element_2.java
66 lines (61 loc) · 1.47 KB
/
majority_element_2.java
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
/**
* Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
*
*
*
* Example 1:
*
* Input: nums = [3,2,3]
* Output: [3]
* Example 2:
*
* Input: nums = [1]
* Output: [1]
* Example 3:
*
* Input: nums = [1,2]
* Output: [1,2]
*
*
* Constraints:
*
* 1 <= nums.length <= 5 * 104
* -109 <= nums[i] <= 109
*/
package InterviewProblems;
import java.util.ArrayList;
import java.util.List;
public class MajorityElement2 {
public static void main(String[] args) {
int[] nums = {1,2};
List<Integer> ans = solve(nums);
System.out.println(ans);
}
public static List<Integer> solve(int[] nums) {
// O(N) time | O(1) space
int num1 = -1, num2 = -1, count1 = 0, count2 = 0, len = nums.length;
for (int num : nums) {
if (num == num1) count1++;
else if (num == num2) count2++;
else if (count1 == 0) {
num1 = num;
count1++;
} else if (count2 == 0) {
num2 = num;
count2++;
} else {
count1--;
count2--;
}
}
List<Integer> ans = new ArrayList<>();
count1 = 0; count2 = 0;
for (int num : nums) {
if (num == num1) count1++;
else if (num == num2) count2++;
}
if (count1 > len / 3) ans.add(num1);
if (count2 > len / 3) ans.add(num2);
return ans;
}
}