You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
所以在这题中,写出最后公式是,假如数组1是[a, b],数组2是[c, d]: (a ^ c) ^ (a ^ d) ^ (b ^ c) ^ (b ^ d) = ?
其实其等于a ^ c ^ a ^ d ....,把括号拆除。这样就可以用异或来简化算法了。观察!
class Solution {
public int xorAllNums(int[] nums1, int[] nums2) {
int n1 = nums1.length;
int n2 = nums2.length;
int res = 0;
if (n2 % 2 != 0) {
for (int n : nums1) {
res ^= n;
}
}
if (n1 % 2 != 0) {
for (int n : nums2) {
res ^= n;
}
}
return res;
}
}
这道题咋一看很复杂。运算全是异或。我一开始想计算每个位置的1和0的出现次数,再运算,但显然太复杂了。
细想一下,异或的关键在于异或自身偶数次结果为0,异或自身寄次数结果为自身。
所以在这题中,写出最后公式是,假如数组1是[a, b],数组2是[c, d]: (a ^ c) ^ (a ^ d) ^ (b ^ c) ^ (b ^ d) = ?
其实其等于a ^ c ^ a ^ d ....,把括号拆除。这样就可以用异或来简化算法了。观察!
The text was updated successfully, but these errors were encountered: