- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathMajority_Element.java
34 lines (32 loc) · 869 Bytes
/
Majority_Element.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
/*
* Question:
* Given an array nums of size n, return the majority element.
* The majority element is the element that appears more than ⌊n / 2⌋ times.
*
* I have solved this question and even optimised it using the famous Algorithm known as
* "Moore's Voting Algorithm"
*
* LeetCode Q - 169
*
*
* Time Complexity - O(N)
* Space Complexity - O(1)
*/
publicclassMajority_Element {
publicstaticvoidmain(String[] args) {
intarr[] = { 2, 2, 1, 1, 1, 2, 2 };
System.out.println(majority(arr));
}
publicstaticintmajority(intnums[]) {
intc = 0, elm = 0;
for (inti = 0; i < nums.length; i++) {
if (c == 0)
elm = nums[i];
if (elm == nums[i])
c++;
else
c--;
}
returnelm;
}
}