Hello codes, Today I am going to solve another Leetcode problem ” Majority Element Leetcode Solution “. The solution will be in java.
Problem statement:
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 Explanation: Here, you can clearly see 3 comes 2 times and 2 comes 1 time. Hence, 3 is the majority element in the given array.
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Majority Element Leetcode Solution java
import java.util.*; class Solution { int majorityElement(int[] nums) { int index=0; int count=1; for(int i=1;i<nums.length;i++){ if(nums[index]==nums[i]){ count+=1; } else{ count-=1; } if(count==0){ index=i; count=1; } } return nums[index]; } }
Disclaimer: This problem(Majority element Leetcode solution) is originally created by Leetcode. Codesagar only provides a solution for it. This solution is only for Educational and learning purposes.