leetcode 810. Chalkboard XOR Game

leetcode 810. Chalkboard XOR Game


原题地址:https://leetcode.com/problems/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.

Note:

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

    这道题有些歧义,几位大佬在讨论为啥[1,2,3]的结果是true,他们认为最开始是一定由Alice开始的,可是要想解这道题,如果最开始结果就是0的话,那么就直接默认Alice赢,所以[1,2,3]的结果为true。
    判断初始条件,只要初始结果不为零,那么一定存在两个不相同的nums[i],这时候只要去选与结果不同的即可。多以只要给定数组为偶数个,那么Alice就可以赢,奇数的话Alice擦掉一个数后就相当于Bob站在了偶数个时候Alice的角度,所以Bob赢。如果只考虑数组长度,就会造成[1,2,3]返回false的情况。

python代码

class Solution:
    def xorGame(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        result = 0
        for i in nums: 
            result = result ^ i
        if result == 0 or len(nums) % 2 == 0:
            return True
        else:
            return False

版权声明:转载注明 http://blog.csdn.net/birdreamer/article/details/79781069

你可能感兴趣的:(leetcode,python)