169. Majority Element

 

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;
    }
}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50