Advertisement
alisadafi

Majority-Element-D&C

Nov 9th, 2023 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.44 KB | None | 0 0
  1. from typing import List
  2.  
  3. def majority(A: List[int], l: int, r: int):
  4.     if l == r:
  5.         return A[l]
  6.     mid = (l + r) // 2
  7.     a = majority(A, mid + 1, r)
  8.     b = majority(A, l, mid)
  9.     if a == b:
  10.         return a
  11.     count_a = 0
  12.     count_b = 0
  13.     for i in range(l, r + 1):
  14.         if A[i] == a:
  15.             count_a += 1
  16.         elif A[i] == b:
  17.             count_b += 1
  18.     if count_a > (r - l + 1) / 2:
  19.         return a
  20.     elif count_b > (r - l + 1) / 2:
  21.         return b
  22.     else:
  23.         return -1 # not found
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement