-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathMajorityElement.java
92 lines (63 loc) · 1.64 KB
/
MajorityElement.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
Source: https://leetcode.com/problems/majority-element/
Approach 1 (using extra space by taking map)
Time: O(n), where n is the length of the given vector(nums)
Space: O(n), map is required to store the frequency of each element
*/
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
int majorityElement = 0;
int halfLen = nums.length >> 1;
for(int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
if(map.get(num) > halfLen) {
majorityElement = num;
break;
}
}
return majorityElement;
}
}
/*
Approach 2 (More optimized than approach 1 without using map)
Time: O(n), where n is the length of the given vector(nums)
Space: O(1), in-place
*/
class Solution {
public int majorityElement(int[] nums) {
int majorityElement = nums[0];
int count = 1;
int len = nums.length;
for(int i = 1; i < len; ++i) {
if(count == 0) {
majorityElement = nums[i];
}
count += (nums[i] == majorityElement) ? 1 : -1;
}
return majorityElement;
}
}
/*
Slight modification to make it more optimized than approach 2
Time: O(n), where n is the length of the given vector(nums)
Space: O(1), in-place
*/
class Solution {
public int majorityElement(int[] nums) {
int majorityElement = nums[0];
int count = 1;
int len = nums.length;
for(int i = 1; i < len; ++i) {
if(count == 0) {
majorityElement = nums[i];
count = 1;
} else if(nums[i] != majorityElement) {
--count;
} else {
++count;
}
}
return majorityElement;
}
}