169. Majority Element
- Get link
- X
- Other Apps
Intuition
there is only one element which can be more than n/2
Approach
count the index element if it matches i+1 increse count ++ or count -- if count again reaches 0 assign the present element as majority element and return it
Complexity
- Time complexity: O(n)
- Space complexity: O(1)
Code
Java
class Solution {
public int majorityElement(int[] nums) {
int majority = 0;
int count = 0;
for(int i = 0; i<nums.length; i++){
if(count == 0){
majority = nums[i];
}
if(nums[i] == majority){
count++;
}else{
count--;
}
}
return majority;
}
}- Get link
- X
- Other Apps
Comments
Post a Comment