-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajorityElement.java
More file actions
31 lines (25 loc) · 905 Bytes
/
majorityElement.java
File metadata and controls
31 lines (25 loc) · 905 Bytes
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
class Solution {
// Function to find the majority element in an array
public int majorityElement(int[] nums) {
// Size of the given array
int n = nums.length;
// Iterate through each element of the array
for (int i = 0; i < n; i++) {
// Counter to count occurrences of nums[i]
int cnt = 0;
// Count the frequency of nums[i] in the array
for (int j = 0; j < n; j++) {
if (nums[j] == nums[i]) {
cnt++;
}
}
// Check if frequency of nums[i] is greater than n/2
if (cnt > (n / 2)) {
// Return the majority element
return nums[i];
}
}
// Return -1 if no majority element is found
return -1;
}
}