跳至主要內容

136. 只出现一次的数字

T4mako算法位运算数组小于 1 分钟

136. 只出现一次的数字

简单

题目描述open in new window

解法:异或

  • 异或交换律:a ^ b ^ c = a ^ c ^ b

  • 任何数于 0 异或为任何数 0 ^ n = n

  • 相同的数异或为 0: n ^ n = 0

class Solution {
    public int singleNumber(int[] nums) {
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            res ^= nums[i];
        }
        return res;
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5