Skip to content

Commit 10faa02

Browse files
authored
Merge pull request #66 from TORRYNN/Divide
Majority Element using Bruteforce
2 parents ba619f5 + 4b0b67a commit 10faa02

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
652 Bytes
Binary file not shown.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class PracticeQs2 {
2+
// Brute Force Approach
3+
// Idea: Count the number of times each number occurs in the array & find the largest count.
4+
// Time Complexity:O(n2);
5+
public static int MajorityElement(int[] nums) {
6+
// We know that majorit count we be more than half of the element.
7+
int majoritycount = nums.length / 2;
8+
9+
for (int i = 0; i < nums.length; i++) {
10+
int count = 0;
11+
for (int j = 0; j < nums.length; j++) {
12+
if (nums[i] == nums[j]) {
13+
count++;
14+
}
15+
}
16+
if (count > majoritycount) {
17+
return nums[i];
18+
}
19+
}
20+
return -1;
21+
22+
}
23+
24+
public static void main(String[] args) {
25+
int nums[] = { 2, 2, 1, 1, 1, 2, 2 };
26+
System.out.println(MajorityElement(nums));
27+
}
28+
}

0 commit comments

Comments
 (0)