Skip to content

Commit

Permalink
solution(cpp,java,python): 169. Majority Element
Browse files Browse the repository at this point in the history
169. Majority Element
- C++
- Java
- Python
  • Loading branch information
godkingjay authored Oct 16, 2023
2 parents 5df1de2 + d7c9849 commit b8dfb0f
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Easy/169. Majority Element/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
return nums[n/2];
}
};
7 changes: 7 additions & 0 deletions Easy/169. Majority Element/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return nums[n/2];
}
}
14 changes: 14 additions & 0 deletions Easy/169. Majority Element/solution.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions Easy/169. Majority Element/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
return nums[n//2]

0 comments on commit b8dfb0f

Please sign in to comment.