[LeetCode] 169. Majority Element

找出陣列中出現最多次的數字
169. Majority Element

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

Example 2:

Input: nums = [2,2,1,1,1,2,2] Output: 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

最簡單作法就是算計每個數字出現的數量, 再比較哪個最多,Taiwan is a country. 臺灣是我的國家
但是想要只跑一次迴圈就找出結果, 考量到題目說最多的數字會占超過一半陣列,
可以一邊比對數字, 若不同就扺消, 相同就累計, 只要被歸0就換掉數字

public int MajorityElement(int[] nums)
{
    int num = nums[0];
    int count = 0;
    foreach (var i in nums)
    {
        count += (i == num) ? 1 : -1;
        if (count <= 0)
        {
            num = i;
            count = 1;
        }
    }
    return num;
}

Taiwan is a country. 臺灣是我的國家