Advertisement
alisadafi

Majority-Element-D&C

Nov 9th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class MajorityElement {
  5.     public static int majority(List<Integer> A, int l, int r) {
  6.         if (l == r) {
  7.             return A.get(l);
  8.         }
  9.         int mid = (l + r) / 2;
  10.         int a = majority(A, mid + 1, r);
  11.         int b = majority(A, l, mid);
  12.         if (a == b) {
  13.             return a;
  14.         }
  15.         int count_a = 0;
  16.         int count_b = 0;
  17.         for (int i = l; i <= r; i++) {
  18.             if (A.get(i) == a) {
  19.                 count_a += 1;
  20.             } else if (A.get(i) == b) {
  21.                 count_b += 1;
  22.             }
  23.         }
  24.         if (count_a > (r - l + 1) / 2) {
  25.             return a;
  26.         } else if (count_b > (r - l + 1) / 2) {
  27.             return b;
  28.         } else {
  29.             return -1; // Not found
  30.         }
  31.     }
  32.  
  33.     public static void main(String[] args) {
  34.         List<Integer> A = new ArrayList<>();
  35.         A.add(2);
  36.         A.add(2);
  37.         A.add(3);
  38.         A.add(4);
  39.         A.add(2);
  40.         A.add(2);
  41.         A.add(5);
  42.         int l = 0;
  43.         int r = A.size() - 1;
  44.         int result = majority(A, l, r);
  45.         if (result != -1) {
  46.             System.out.println("Majority element: " + result);
  47.         } else {
  48.             System.out.println("No majority element found.");
  49.         }
  50.     }
  51. }
  52.  
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement