169. Majority Element
多數元素是指在數組中出現次數超過 ⌊n / 2⌋ 次的元素。你可以假設數組中總是存在多數元素。
範例 :
輸入:nums = [3,2,3]
輸出:3
輸入:nums = [3,2,3]
輸出:3
Python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
17.95MB, 169ms
C++
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
};
26.53MB, 11ms
Javascript
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let count = 0;
let candidate = null;
for (let num of nums) {
if (count === 0) {
candidate = num;
}
count += (num === candidate) ? 1 : -1;
}
return candidate;
};
52.81MB, 53ms