[Swift]LeetCode810. 黑板異或遊戲 | Chalkboard XOR Game

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-dxwmghyc-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.)git

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.github

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.

一個黑板上寫着一個非負整數數組 nums[i] 。小紅和小明輪流從黑板上擦掉一個數字,小紅先手。若是擦除一個數字後,剩餘的全部數字按位異或運算得出的結果等於 0 的話,當前玩家遊戲失敗。 (另外,若是隻剩一個數字,按位異或運算獲得它自己;若是無數字剩餘,按位異或運算結果爲 0。)spa

換種說法就是,輪到某個玩家時,若是當前黑板上全部數字按位異或運算結果等於 0,這個玩家獲勝。code

假設兩個玩家每步都使用最優解,當且僅當小紅獲勝時返回 true。htm

示例:
輸入: nums = [1, 1, 2]
輸出: false
解釋: 
小紅有兩個選擇: 擦掉數字 1 或 2。
若是擦掉 1, 數組變成 [1, 2]。剩餘數字按位異或獲得 1 XOR 2 = 3。那麼小明能夠擦掉任意數字,由於小紅會成爲擦掉最後一個數字的人,她老是會輸。
若是小紅擦掉 2,那麼數組變成[1, 1]。剩餘數字按位異或獲得 1 XOR 1 = 0。小紅仍然會輸掉遊戲。

說明:blog

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

Runtime: 68 ms
Memory Usage: 18.7 MB
 1 class Solution {
 2     func xorGame(_ nums: [Int]) -> Bool {
 3         var x:Int = 0
 4         var n:Int = nums.count
 5         for num in nums
 6         {
 7             x ^= num
 8         }
 9         return x == 0 || n % 2 == 0
10     }
11 }

68ms遊戲

1 class Solution {
2     func xorGame(_ nums: [Int]) -> Bool {
3         return nums.count % 2 == 0 || nums.reduce(0, ^) == 0
4     }
5 }
相關文章
相關標籤/搜索