Skip to content

Commit 1365f9c

Browse files
Merge pull request #281 from nik132-eng/patch-5
Create Majority_Element_II.java
2 parents 5b1fad9 + dd0e070 commit 1365f9c

1 file changed

Lines changed: 87 additions & 0 deletions

File tree

LeetCode/Majority_Element_II.java

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
2+
//229. Majority Element II
3+
//Given an integer array of size n, find all elements that appear more than ⌊ n/3⌋ times.
4+
5+
//Example 1:
6+
7+
//Input: nums = [3,2,3]
8+
//Output: [3]
9+
//Example 2:
10+
11+
//Input: nums = [1]
12+
//Output: [1]
13+
//Example 3:
14+
15+
//Input: nums = [1,2]
16+
//Output: [1,2]
17+
18+
//Constraints:
19+
20+
//1 <= nums.length <= 5 * 104
21+
//-109 <= nums[i] <= 109
22+
23+
import java.util.*;
24+
25+
public class Majority_Element_II {
26+
27+
public static void main(String[] args) {
28+
Scanner sc = new Scanner(System.in);
29+
30+
System.out.println("Enter Number of element : ");
31+
int n = sc.nextInt();
32+
33+
int nums[] = new int[n];
34+
System.out.println("Enter " + n + " values :");
35+
for (int i = 0; i < n; i++) {
36+
nums[i] = sc.nextInt();
37+
}
38+
List<Integer> ans = majorityElement_II(nums);
39+
40+
System.out.println("Majority Element is : " + ans);
41+
}
42+
43+
public static List<Integer> majorityElement_II(int[] nums) {
44+
45+
// take variables
46+
int num1 = -1, num2 = -1, c1 = 0, c2 = 0, len = nums.length;
47+
// run foreach loop
48+
for (int el : nums) {
49+
// for first time check with the num1 if the numbers are same than increment in c1(count 1)
50+
// else if first time check with the num2 if the numbers are same than increment in c2(count 2)
51+
// if c1 is the first element so value of num1 is same as e1 and same for e2
52+
if (el == num1)
53+
c1++;
54+
else if (el == num2)
55+
c2++;
56+
else if (c1 == 0) {
57+
num1 = el;
58+
c1 = 1;
59+
} else if (c2 == 0) {
60+
num2 = el;
61+
c2 = 1;
62+
} else {
63+
c1--;
64+
c2--;
65+
}
66+
}
67+
// make list for the find all elements that appear more than ⌊ n/3⌋ times.
68+
List<Integer> ans = new ArrayList<Integer>();
69+
c1 = 0;
70+
c2 = 0;
71+
for (int el : nums) {
72+
if (el == num1)
73+
c1++;
74+
else if (el == num2)
75+
c2++;
76+
}
77+
// checking the conditition
78+
if (c1 > len / 3)
79+
ans.add(num1);
80+
if (c2 > len / 3)
81+
ans.add(num2);
82+
83+
return ans;
84+
85+
}
86+
87+
}

0 commit comments

Comments
 (0)