From ee93987c0bf3a7640f5cf64f79ec6676cf56a31d Mon Sep 17 00:00:00 2001 From: Laxmikant Dubey <132117545+Laxmikant3@users.noreply.github.com> Date: Mon, 28 Apr 2025 11:58:48 +0530 Subject: [PATCH] Create Majority_Element.cpp --- 25. Divide and Conquer/Majority_Element.cpp | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 25. Divide and Conquer/Majority_Element.cpp diff --git a/25. Divide and Conquer/Majority_Element.cpp b/25. Divide and Conquer/Majority_Element.cpp new file mode 100644 index 00000000..eda732c7 --- /dev/null +++ b/25. Divide and Conquer/Majority_Element.cpp @@ -0,0 +1,27 @@ +public class Solution { + public int majorityElement(int[] num) { + int major = num[0], count = 1; + for (int i = 1; i < num.length; i++) { + if (count == 0) { + count++; + major = num[i]; + } else if (major == num[i]) { + count++; + } else { + count--; + } + } + return major; + } + + public static void main(String[] args) { + // Create an instance of the Solution class + Solution solution = new Solution(); + + // Example input array + int[] nums = {3, 2, 3}; + + // Call the majorityElement method and print the result + System.out.println("Majority Element: " + solution.majorityElement(nums)); // Output: 3 + } +}