From c3b77367a18503ef6885318ffc254bb2c5719064 Mon Sep 17 00:00:00 2001 From: Aayush Date: Sun, 13 Jun 2021 14:36:53 +0530 Subject: [PATCH] chore(java): add majority element (#354) --- algorithms/Java/README.md | 1 + algorithms/Java/arrays/majority-element.java | 70 ++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 algorithms/Java/arrays/majority-element.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 49f8b80d..51294f90 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -6,6 +6,7 @@ 2. [Kadanes Algorithm](arrays/kadanes-algorithm.java) 3. [Left Rotation](arrays/left-rotation.java) 4. [Unique Digits of Large Number](arrays/unique-digits-of-large-number.java) +5. [Majority Element](arrays/majority-element.java) ## Graphs diff --git a/algorithms/Java/arrays/majority-element.java b/algorithms/Java/arrays/majority-element.java new file mode 100644 index 00000000..c4533f6a --- /dev/null +++ b/algorithms/Java/arrays/majority-element.java @@ -0,0 +1,70 @@ +//Given an array A of N elements. Find the majority element in the array. +//A majority element in an array A of size N is an element that appears more than N/2 times in the array + +// Moore’s Voting Algorithm => Time Complexity: O(n), Space Complexity: O(1) + +import java.util.*; +import java.io.*; +import java.lang.*; + +class Main { + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + + while(t-- > 0) { + int n =sc.nextInt(); + int arr[] = new int[n]; + + for(int i = 0; i < n; i++) + arr[i] = sc.nextInt(); + + System.out.println(new Solution().majorityElement(arr, n)); + } + } +} + +class Solution +{ + static int majorityElement(int a[], int size){ + int cand = findCand(a, size); + if(isMajority(a, size, cand)) + return cand; + return -1; + } + + static int findCand(int arr[], int n){ + int max_index=0; int count=1; + for(int i=1; i n/2) return true; + return false; + } +} + +/* Test Case: +Input: +N = 5 A[] = {3,1,3,3,2} + +Output: 3 + +Explanation: +Since, 3 is present more +than N/2 times, so it is +the majority element. */ \ No newline at end of file