0%

异或操作的算法应用

题一

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class N136 {

public int singleNumber(int[] nums) {
int ans=nums[0];
if(nums.length>1){
for(int i=1;i<nums.length;i++){
ans=ans^nums[i];
}
}
return ans;

}
}

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

题二

给你一个整数数组 arr

现需要从数组中取三个下标 ijk ,其中 (0 <= i < j <= k < arr.length)

ab 定义如下:

  • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
  • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]

注意:^ 表示 按位异或 操作。

请返回能够令 a == b 成立的三元组 (i, j , k) 的数目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static int countTriplets(int[] arr) {

int res=0;

if(arr.length<2){
return 0;
}
for(int i=0;i<arr.length;i++){
int temp=arr[i];
for(int j=i+1;j<arr.length;j++){
temp=temp^arr[j];
if(temp==0){
res=res+j-i;
}
}

}
return res;

}

https://leetcode-cn.com/classic/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/description/?tdsourcetag=s_pctim_aiomsg