C# solution: candidate & count


  • 0
    B
    public class Solution 
    {
        public int MajorityElement(int[] nums) 
        {
            var candidate = nums[0];
            var candidateCount = 1;
            for (int i = 1; i < nums.Length; i++)
            {
                if (nums[i] == candidate)
                {
                    candidateCount++;
                }
                else
                {
                    candidateCount--;
    
                    if (candidateCount == 0)
                    {
                        candidate = nums[i];
                        candidateCount = 1;
                    }
                }
            }
    
            return candidate;
        }
    }
    

Log in to reply
 

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