欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

leetcode 260. Single Number III | 260. 只出现一次的数字 III(位运算:分组异或)

发布时间:2024/2/28 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 260. Single Number III | 260. 只出现一次的数字 III(位运算:分组异或) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

https://leetcode.com/problems/single-number-iii/

题解:分组异或

参考1:讨论区题解
you know you can eliminate doubles with xor so do that first. whats left over is xor of the two single numbers. between those, there must be 1 bit that is set thats unique to that number. set a mask for that bit and xor again with only numbers that have that bit set. you will then find the first number. the first xor is xor of the two numbers. so xor it one more time with the first number to get the other number

参考2:官方题解

class Solution {public int[] singleNumber(int[] nums) {int xor = 0;for (int n : nums)xor ^= n;int a = xor;int b = xor; // int sn = -1; // 方法1:最高位1对应的索引位置 // while (xor != 0) { // xor >>>= 1; // sn++; // } // int mask = 1 << sn; // 选择最高位1所在的位置为maskint mask = 1; // 方法2:选择最低位1所在的位置为maskwhile ((mask & xor) == 0)mask = mask << 1;for (int n : nums) {if ((n & mask) == 0) a ^= n;else b ^= n;}return new int[]{a, b};} }

总结

以上是生活随笔为你收集整理的leetcode 260. Single Number III | 260. 只出现一次的数字 III(位运算:分组异或)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。