-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority element.java
More file actions
70 lines (50 loc) · 1.37 KB
/
majority element.java
File metadata and controls
70 lines (50 loc) · 1.37 KB
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
# practice_problem-DSA
leetcode-day1
# majority element-
//1.Using Boyer–Moore Majority Vote Algorithm-time complexity-O(n)
class Solution {
public int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
if (num == candidate) {
count++;
} else {
count--;
}
}
return candidate;
}
}
// 2.Sorting Approch-Time Complexity: O(n log n)
import java.util.Arrays;
public class MajorityElement {
public static void main(String[] args) {
int nums[] = {1,2,2,1,1};
Arrays.sort(nums); // sorting
int n = nums.length;
System.out.println("Majority element: " + nums[n/2]);
}
}
//3.Brute Force approch - Time: O(n²)
public class MajorityElementBrute {
public static void main(String[] args) {
int nums[] = {1, 2, 2, 1, 1};
int n = nums.length;
for(int i = 0; i < n; i++){
int count = 0;
for(int j = 0; j < n; j++){
if(nums[i] == nums[j]){
count++;
}
}
if(count > n/2){
System.out.println("Majority element: " + nums[i]);
return;
}
}
}
}