LeetCode#169. Majority Element(超过数组长度一半的元素)

  • 题目:给定一个数组,并且数组中存在一个元素,该元素在数组中的出现次数超过数组长度的一半(n/2)
  • 难度:Easy
  • 思路:A Fast Ma jority Vote Algorithm 数组中相邻的两个元素,如果元素值不同,则可以相互抵消。经过抵消后,剩余元素一定是那个要寻找的元素。另一种思路可参考https://bestswifter.com/arrayoccurmorethanhalf/
  • 代码:
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 1;
        int max = nums[0];
        for(int i = 1; i < nums.size(); i++){
            if(count == 0){
                count++;
                max = nums[i];
            }else if (max == nums[i]){
                count++;
            }else{
                count--;
            }
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/u012559634/article/details/79501705