Question

Please solve using Java and comment your code for clarity.

Sample 3. Input: 4 1 231 Output: 0 This sequence also does not have a majority element (note that the element 1 appears twice

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Once we find majority element we check again isMajority or not using isMajority() function

import java.util.*;
class Solution {
    public static int count(int[] a, int num, int lo, int hi) {
        int frequency = 0;
        for (int i = lo; i <= hi; i++) {
            if (a[i] == num) {
                frequency++;
            }
        }
        return frequency;
    }

    public static int majorityElementRec(int[] a, int lo, int hi) {
        // base case; the only element in an array of size 1 is the majority
        // element.
        if (lo == hi) {
            return a[lo];
        }

        // recurse on left and right halves of this slice.
        int mid = (hi-lo)/2 + lo;
        int left = majorityElementRec(a, lo, mid);
        int right = majorityElementRec(a, mid+1, hi);

        // if the two halves agree on the majority element, return it.
        if (left == right) {
            return left;
        }

        // otherwise, count each element and return the "winner".
        int leftCount = count(a, left, lo, hi);
        int rightCount = count(a, right, lo, hi);

       if(leftCount>rightCount){
           return left;
       }
       return right;
    }
  
  
   public static boolean isMajority(int a[], int size, int cand)
    {
        int i, frequency = 0;
        for (i = 0; i < size; i++)
        {
            if (a[i] == cand)
                frequency++;
        }
        if (frequency > size / 2) {
            return true;
        }
        else{
            return false;
        }
    }
  
    public static int majorityElement1(int[] a) {
        if(isMajority(a,a.length,majorityElementRec(a, 0, a.length-1))){
           return 1;
        }else{
           return 0;
        }
    }
  
    public static int majorityElement2(int[] a) {
        int count = 0;
        int ans = -1;

        for (int num : a) {
            if (count == 0) {
                ans = num;
            }
            count += (num == ans) ? 1 : -1;
        }
       if(isMajority(a,a.length,ans)==false){
           ans=0;
       }else{
           ans=1;
       }
        return ans;
    }
    public static void main(String []args){
       Scanner sc=new Scanner(System.in);
      
       int n=sc.nextInt();
       int a[]=new int[n];
       for(int i=0;i<n;i++){
           a[i]=sc.nextInt();
       }
       /*
       We split the array A into 2 subarraysA1andA2of half the size.
       We choose the majority element ofA1andA2.
       After that we do a linear time equality operation to decide whether it is possible to find a majorityelement.
       The recurrence therefore is given by
       T(n) = 2T(n2) +O(n)
      
       So The complexity of algorithm is O(nlogn)
      
       */
       int ans=0;
       int maj=majorityElement1(a);
       System.out.println("Using O(nlogn) solution :"+ans);
       /*
      
       Idea of the algorithm is that if each occurrence of an element e
       can be cancelled with all the other elements that are different from e
       then e will exist till end if it is a majority element
      
       */
       int maj1=majorityElement2(a);
       System.out.println("Using O(n) solution :"+" "+maj1);
      
    }
}

Add a comment
Know the answer?
Add Answer to:
Please solve using Java and comment your code for clarity. Sample 3. Input: 4 1 231...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • ALGORITHM PROBLEM: A) Significant Inversions: We are given a sequence of n arbitrary but distinct real...

    ALGORITHM PROBLEM: A) Significant Inversions: We are given a sequence of n arbitrary but distinct real numbers <a1 , a2 ,..., an>. We define a significant inversion to be a pair i < j such that ai > 2 aj . Design and analyze an O(n log n) time algorithm to count the number of significant inversions in the given sequence. [Hint: Use divide-&-conquer. Do the “combine” step carefully] B) The Maximum-Sum Monotone Sub-Array Problem: Input: An array A[1..n] of...

  • the two problems are related. Please explain your answer in full detail Problem 1: On input...

    the two problems are related. Please explain your answer in full detail Problem 1: On input a Binary Search Tree T show how to output an array that contains all the elements in T in sorted order. What's the running time of your algorithm? Does it perform any comparisons? Problem 2: Your classmate claims that they have an algorithm that on input n elements, constructs a Binary Search Tree T with those n elements using only O(n) comparisons. Can you...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

  • Consider n indivisible objects with distinct types i = 1, 2, 3,…, n. We are given...

    Consider n indivisible objects with distinct types i = 1, 2, 3,…, n. We are given positive integer weights W = {w1,w2...wn} and positive integer prices V = {v1,v2...vn} for the objects and a knapsack of weight capacity (m). Our problem is to find the maximum profit possible by including a subset of the objects into the knapsack with total weight of at most m. This form of the 0/1 Knapsack Problem can be solved by a Decrease and Conquer...

  • Problem 5: Recurrence relations and detailed analysis of recursive algorithm efficiency                 g(n: non-negative integer)        &nbsp

    Problem 5: Recurrence relations and detailed analysis of recursive algorithm efficiency                 g(n: non-negative integer)                 1. if n ≤ 1 then return n                 2. else return (5 * g(n─1) ─ 6 * g(n─2)) MergeSort divides the array to be sorted into two equal halves, calls itself recursively on each half to sort that subarray, and then calls the Merge algorithm to merge the two sorted halves in linear time. This leads to its two recurrence relations T(n)=2T(n/2)+cn, n>1;...

  • PLEASE HELP!!! C PROGRAMMING CODE!!! Please solve these functions using the prototypes provided. At the end...

    PLEASE HELP!!! C PROGRAMMING CODE!!! Please solve these functions using the prototypes provided. At the end please include a main function that tests the functions that will go into a separate driver file. Prototypes int R_get_int (void); int R_pow void R Jarvis int start); void R_fill_array(int arrayll, int len); void R_prt_array (int arrayl, int len) void R-copy-back (int from[], int to [], int len); int R_count_num (int num, int arrayll, int len) (int base, int ex) 3. Build and run...

  • C Programming Language The code below matches the sample input/output but is marked wrong. Are there...

    C Programming Language The code below matches the sample input/output but is marked wrong. Are there other ways to do this problem? The focus is on recursion and functions. #include<stdio.h> int joCheck(unsigned long long int number) { if(number % 7 == 0 || number % 8 == 0) { return 1; } else return 0; } int main() { int cases = 0; scanf("%d", &cases); for(int i = 1; i<=cases; i++) { unsigned long long int number; scanf("%d", &number); if(joCheck(number)...

  • Code in Java Using Arrays ( input should end with 0 to terminate the program) Bulls...

    Code in Java Using Arrays ( input should end with 0 to terminate the program) Bulls and Cows is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The game is usually played with 4 digits, but can also be played with 3 or any other number of digits. The players must try to guess the secret number created by the codemaker. On a sheet of paper,...

  • C++ PROGRAM ONLY! For this lab you need to write a program that will read in...

    C++ PROGRAM ONLY! For this lab you need to write a program that will read in two values from a user and output the greatest common divisor (using a recursive implementation of the Euclidean algorithm) to a file. In Lab #3, you implemented this program using an iterative method. Greatest Common Divisor In mathematics, the greatest common divisor (GCD) of two or more integers (when at least one of of them is zero then the larger value is the GCD....

  • Algorithm Humble Numbers Problem 4-1 (Humble Numbers) 10 points A number k > 1 is called...

    Algorithm Humble Numbers Problem 4-1 (Humble Numbers) 10 points A number k > 1 is called humble if the only prime factors of k are 3 and 5. Consider the task of on input n, outputting the n smallest humble numbers and the following algorithm to do it: HuMBLE(n) count = 0. pret,Output = 0 HEAP.INSERT (3) HEAP.INSERT (5) while (count < n) cur - HEAP. EXTRACTMIN if cur prevOutput then output cur HEAP,INSERT(3*cur) HEAP.İNSERT(5*cur) count -count+1 preu,Output = cur...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT