-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathMajorityElement.java
51 lines (42 loc) · 937 Bytes
/
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
// @saorav212294
// TC - O(n)
// SC - O(1)
// If an element is majority it will beat out the combined frequency of the rest of the elements in the array
class Solution {
public int majorityElement(int[] nums) {
int count = 1, maj = nums[0];
for (int i = 1; i < nums.length; i++) {
if (maj == nums[i])
count += 1;
else {
count -= 1;
if (count < 0) {
count *= -1;
maj = nums[i];
}
}
}
return maj;
}
}
class Solution {
// TC : O(n)
// SC :O(1)
public int majorityElement(int[] nums) {
int count = 1;
int majorityEl = nums[0];
for(int i=1;i<nums.length;i++) {
int el = nums[i];
if(el == majorityEl){
count++;
} else{
count--;
}
if(count == 0){
majorityEl = nums[i];
count =1;
}
}
return majorityEl;
}
}