169. Majority Element(Solution || Leetcode easy || Java)
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.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
Follow-up: Could you solve the problem in linear time and in O(1)
space?
SOLUTION:
class Solution {
public int majorityElement(int[] nums) {
//if array is consist of just 1 element then return that element
if(nums.length == 1){
return nums[0];
}
//Sort the array
Arrays.sort(nums);
int count = 1;
for(int i = 0; i < nums.length — 1; i++){
if(nums[i] == nums[i+1] ){
count++;
if(count > nums.length/2){//if any element occured more than half the length of array then that element is our answer
return nums[i];
}
}else{
count = 1;
}
}
return count;
}
}
Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.