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.)html
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.spa
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:code
1 <= N <= 1000
. 0 <= nums[i] <= 2^16
.
這道題介紹了一種亦或遊戲,寫在黑板上,(黑板一臉懵逼,跟我有個毛關係)。愛麗絲和鮑勃兩我的輪流擦除一個數字,若是剩下的數字亦或值爲0的話,那麼當前選手就輸了。反過來也能夠這麼說,若是某一個選手開始遊戲時,當前數字的亦或值爲0了,那麼直接就贏了。如今給了咱們一個數組,問先手的愛麗絲可否獲勝。那麼其實這道題是一道有技巧的題,並非讓咱們按照遊戲規則那樣去遍歷全部的狀況,有海量的運算。這題有點像以前那道Nim Game,重要的是技巧!技巧!技巧!重要的事情說三遍~但我等凡夫俗子如何看的出技巧啊,看不出技巧只能看Discuss了,博主也沒看出來。但實際上這道題的解法能夠很是的簡單,兩三行就搞定了。辣麼開始講解吧:首先根據題目的描述,咱們知道了某個選手在開始移除數字以前,若是數組的亦或值爲0的話,選手直接獲勝,那麼先手愛麗絲在開始開始以前也應該檢查一遍數組的亦或值,若是是0的話,直接獲勝。咱們再來分析亦或值不爲0的狀況,既然不爲0,那麼亦或值確定是有一個值的,咱們假設其是x。下面就是本題的精髓了,是要考慮數組個數的奇偶狀況(尼瑪誰能想到!),這個數組個數一旦是偶數的話,就大有文章了,如今數字個數是偶數,且亦或值不爲0,說明數組中的數字不全相同,由於偶數個相同數字的亦或值爲0,那麼愛麗絲只要移除一個不爲x的數字就好了,這樣移除後數組的亦或值也不會是0,那麼因爲鮑勃也是個機智的boy,他也不會移除一個使得剩餘數組亦或值爲0的數字,but,到了最後一個數字時,鮑勃別無選擇只能移除最後一個數字,此時數組爲0,亦或值爲0,愛麗絲獲勝。那此時你可能會有疑問,爲啥奇數個數字且亦或值不爲0時,愛麗絲必定會輸?由於即使愛麗絲先移除掉了一個數字,使得數組亦或值仍不爲0,那麼此時鮑勃面對的狀況就是偶數個數字使得數組亦或值不爲0,這跟上面推論愛麗絲必定會贏的狀況同樣,鮑勃也是個聰明的藍孩紙,因此愛麗絲會輸,參見代碼以下:htm
解法一:blog
class Solution { public: bool xorGame(vector<int>& nums) { int x = 0, n = nums.size(); for (int num : nums) x ^= num; return x == 0 || n % 2 == 0; } };
下面這種解法就很秀了,比大軍師大司馬吳秀波還秀,直接用個accumulate一行搞定亦或值,博主只想吐槽這道題的難度級別,你們有見過一行解出一道Hard題嗎,作夢都要笑醒了吧~遊戲
解法二:element
class Solution { public: bool xorGame(vector<int>& nums) { return nums.size() % 2 == 0 || !accumulate(nums.begin(), nums.end(), 0, bit_xor<int>()); } };
相似題目:leetcode
Nim Gamerem
參考資料:
https://leetcode.com/problems/chalkboard-xor-game/solution/
https://leetcode.com/problems/chalkboard-xor-game/discuss/133807/1-line-C++-solution