From d7c984913a48c1f695212596705fdd78f343e430 Mon Sep 17 00:00:00 2001 From: Vagarth Date: Sun, 15 Oct 2023 08:22:41 +0530 Subject: [PATCH] Solution for Majority Element The solution of Problem-169 Majority Element with descriptive readme and C++, Java and Python code. --- Easy/169. Majority Element/solution.cpp | 8 ++++++++ Easy/169. Majority Element/solution.java | 7 +++++++ Easy/169. Majority Element/solution.md | 14 ++++++++++++++ Easy/169. Majority Element/solution.py | 5 +++++ 4 files changed, 34 insertions(+) create mode 100644 Easy/169. Majority Element/solution.cpp create mode 100644 Easy/169. Majority Element/solution.java create mode 100644 Easy/169. Majority Element/solution.md create mode 100644 Easy/169. Majority Element/solution.py diff --git a/Easy/169. Majority Element/solution.cpp b/Easy/169. Majority Element/solution.cpp new file mode 100644 index 0000000..8b51f02 --- /dev/null +++ b/Easy/169. Majority Element/solution.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int majorityElement(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + return nums[n/2]; + } +}; \ No newline at end of file diff --git a/Easy/169. Majority Element/solution.java b/Easy/169. Majority Element/solution.java new file mode 100644 index 0000000..db4d794 --- /dev/null +++ b/Easy/169. Majority Element/solution.java @@ -0,0 +1,7 @@ +class Solution { + public int majorityElement(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return nums[n/2]; + } +} \ No newline at end of file diff --git a/Easy/169. Majority Element/solution.md b/Easy/169. Majority Element/solution.md new file mode 100644 index 0000000..9d29f0a --- /dev/null +++ b/Easy/169. Majority Element/solution.md @@ -0,0 +1,14 @@ +# PROBLEM + +Given an array nums of size n, return the majority element. + +The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. + +# EXPLANATION + +1. The code begins by sorting the array nums in non-decreasing order using the sort function from the C++ Standard Library. This rearranges the elements such that identical elements are grouped together. + +2. Once the array is sorted, the majority element will always be present at index n/2, where n is the size of the array. +This is because the majority element occurs more than n/2 times, and when the array is sorted, it will occupy the middle position. + +3. The code returns the element at index n/2 as the majority element. \ No newline at end of file diff --git a/Easy/169. Majority Element/solution.py b/Easy/169. Majority Element/solution.py new file mode 100644 index 0000000..8b0b096 --- /dev/null +++ b/Easy/169. Majority Element/solution.py @@ -0,0 +1,5 @@ +class Solution: + def majorityElement(self, nums: List[int]) -> int: + nums.sort() + n = len(nums) + return nums[n//2] \ No newline at end of file