169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊
n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
题目中给定数组必然有某个元素出现的次数占据一半以上。 如果从数组中取出一对不相同的元素,如果这两个元素都不是目标元素,那么取出它们两个之后,目标元素仍然会占据多一半。如果这两个元素中有一个是目标元素,那么取出它们两个之后,目标元素还是会占据多一半。可以每次都取两个元素,如果不同则删去,最后剩下的元素就是目标元素。
class Solution { public: int majorityElement(vector<int>& nums) { int count = 0; int elem = 0; for(int i = 0;i < nums.size(); i++) { if(count == 0) { elem = nums[i]; count++; } else { elem == nums[i]? count++ : count--; } } if(count > 0) return elem; } };