2ms java solution; O(n) time complexity; O(1) additional space complexity


  • -1
    J
    public class Solution {
        public int majorityElement(int[] nums) {
            int result = nums[0], count = 1;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == result) {
                    count++;
                }
                else {
                    count--;
                    if (count == 0) {
                        result = nums[i];
                        count = 1;
                    }
                }
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.