Skip to content

Commit 473a4db

Browse files
Merge pull request #279 from nik132-eng/patch-4
Create Majority_Element.java
2 parents 1365f9c + 9db2061 commit 473a4db

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

LeetCode/Majority_Element.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//169. Majority Element
2+
//
3+
//Given an array nums of size n, return the majority element.
4+
//
5+
//The majority element is the element that appears more than ⌊n / 2⌋ times.
6+
//You may assume that the majority element always exists in the array.
7+
//
8+
//Example 1:
9+
//
10+
//Input: nums = [3,2,3]
11+
//Output: 3
12+
//
13+
//Example 2:
14+
//
15+
//Input: nums = [2,2,1,1,1,2,2]
16+
//Output: 2
17+
//
18+
//
19+
//
20+
//Constraints:
21+
//
22+
//n == nums.length
23+
//1 <= n <= 5 * 104
24+
//-231 <= nums[i] <= 231 - 1
25+
26+
import java.util.Scanner;
27+
28+
public class Majority_Element {
29+
30+
public static void main(String[] args) {
31+
Scanner sc = new Scanner(System.in);
32+
33+
System.out.println("Enter Number of element : ");
34+
int n = sc.nextInt();
35+
36+
int nums[] = new int[n];
37+
System.out.println("Enter " + n + " values :");
38+
for (int i = 0; i < n; i++) {
39+
nums[i] = sc.nextInt();
40+
}
41+
int ans = majorityElement(nums);
42+
43+
System.out.println("Majority Element is : " + ans);
44+
45+
}
46+
47+
private static int majorityElement(int[] nums) {
48+
49+
// take two variables for as key value pair
50+
int count = 0;
51+
int candidate = 0;
52+
// loop
53+
for (int num : nums) {
54+
// if the number apears for the first-time after count value is zero than make it candidate
55+
if (count == 0) {
56+
candidate = num;
57+
}
58+
59+
// if the key(candidate) and the number from the array are same than add one in count else reduce one
60+
if (candidate == num)
61+
count++;
62+
else
63+
count--;
64+
}
65+
return candidate;
66+
}
67+
68+
}

0 commit comments

Comments
 (0)