[Leetcode] 810. Chalkboard XOR Game 解题报告

题目

We are given non-negative integers nums[i] which are written on a chalkboard.  Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first.  If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses.  (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example:
Input: nums = [1, 1, 2]
Output: false
Explanation: 
Alice has two choices: erase 1 or erase 2. 
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. 
If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

Notes:

  • 1 <= N <= 1000
  • 0 <= nums[i] <= 2^16.

思路

这么偏数学和技巧的题目,估计FLAG等公司不会考的。但是分析过程却很有趣:

1)如果xor == 0,那就说明Alice已经赢了,因为上一把Bob的行为已经导致了xor == 0。

2)如果xor != 0,并且数组的长度为偶数,那么Alice一定会赢。这是因为:当数组长度为偶数的时候,不可能所有的数都相同(否则xor == 0)。此时Alice总是可以找到两个不同的数,并且erase掉其中一个,这样一定不会引起xor == 0。所以Alice一定会赢。

再看看如果xor != 0 && nums.size() % 2 != 0的时候,会发生什么吧:Alice此时会被迫擦掉一个数,如果擦掉的这个数引起了xor == 0,那么她就立刻输了;否则她擦掉的数虽然不会导致xor == 0,但是此时数组中剩下了偶数个元素,那么Bob就可以采用和Alice相同的策略把Alice干掉,因为此时xo != 0 && nums.size() == 0,满足上面分析中的条件2)。

所以Alice会赢当且仅当xor == 0 || nums.size() % 2 == 0。

代码

class Solution {
public:
    bool xorGame(vector<int>& nums) {
        int xo = 0;
        for (int n: nums) {
            xo ^= n;
        }
        return xo == 0 || nums.size() % 2 == 0;
    }
};

猜你喜欢

转载自blog.csdn.net/magicbean2/article/details/79861563