Leetcode 169 Majority Element

这是一道摩尔投票的题目。 后续题目229.Majority Element II

static int x = [] () {ios::sync_with_stdio(false); cin.tie(0); return 0;} ();
class Solution {
 public:
  int majorityElement(vector<int>& nums) {
    int res = nums[0], count = 1;
    for (int i = 1, stop = nums.size(); i < stop; ++i) {
      if (nums[i] == res) {
        ++count;
      } else {
        --count;
        if (count == 0) {
          res = nums[i];
          count = 1;
        }
      }
    }
    return res;
  }
};

直达链接

LeetCode 169. Majority Element

摩尔投票

找出一组数组中,出现次数超过数组长度一半的那个数,时间复杂度O(n)\mathcal{O}(n),空间复杂度O(1)\mathcal{O}(1),这种算法存在,叫摩尔投票 ( Moore voting )。

算法核心思想:所有选票中,不同的选票两两抵消,最后剩下的那张选票,就是选出的得票最多的那个人。

Leetcode 1025 Divisor Game

当某个人遇到1时,他一定输了,当某个人遇到2时,他一定赢了。奇数的因子都是奇数(因为奇数不能被2整除,而偶数能被2整除。一个偶数无论与谁相乘,积的因子一定有2,所以奇数的因子一定不会是偶数),而一个奇数减去他的奇数因子,会得到偶数,这时候轮到另一个人玩了。偶数减去1一定变成奇数,所以奇数开局时,先玩的那个人一定输。

Leetcode 421 Maximum Xor of Two Numbers in an Array

两重循环,得出结果,结果题目中问能不能在O(n)\mathcal{O}(n)时间内解决。也对,两重循环也没意思。

不过,还是先试试,最容易想到的算法结果怎么样,这个算法的时间复杂度是O(n2)\mathcal{O}(n^2)。自己亦或自己的结果是0,所以初始化res = 0就包括了所有i = j的情况。