Leetcode's 188th weekly contest [Number of triples forming two XOR arrays]

The number of triples forming two XOR equal arrays

The problem this time feels a lot harder than last week, mainly because of bad math. After reading the solutions of others, without looking at the code, I immediately passed the code again. Record it now and remind yourself to study mathematics well in the future (don’t laugh at the boss).

First look at the title description:

给你一个整数数组 arr 。
现需要从数组中取三个下标 i、j 和 k ,其中 (0 <= i < j <= k < arr.length)

a 和 b 定义如下:

a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
注意:^ 表示 按位异或 操作。

请返回能够令 a == b 成立的三元组 (i, j , k) 的数目。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor

Example:


输入:arr = [2,3,1,6,7]
输出:4
解释:满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)

The math is not good at first glance, it feels so difficult, because it is necessary to obtain the XOR value of all the elements in arr[i ~ j-1] and arr[j~k], and also perform the XOR value of the two parts. By contrast, I felt my head exploded at first glance (I don’t know others, I exploded anyway)

Let's look at the following theorem and our understanding of the topic:
(1) The inverse proposition of a == b is a ^ b == 0;
(2) a == b is introduced: a ^ b == 0; arr[i]^arr[i+1]… ^arr[j-1] ^arr[j]… ^ arr[k] == 0;

The essence is here (the third point has nothing to do with XOR, it is purely to test the understanding of the topic):
(3) When arr[i]^…arr[k] = 0, i, k, this At the beginning and end of the triple, each position of j is an answer.
Because 0 <= i <j <= k, there are always ki positions of j, that is, a triple of k-i.

As long as you understand the above three sentences, you will understand the idea of ​​the ontology.
The following is the code implemented in C++.

int countTriplets(vector<int>& arr) {
    
    
	if (arr.size() < 2)
		return 0;
	int count2 = 0;
	int temp;
	for (int i = 0; i < arr.size(); i++) {
    
    
		temp = arr[i];	//以 arr[i] 为开头
		for (int j = i + 1; j < arr.size(); j++) {
    
    
			temp ^= arr[j];
			if (temp == 0) {
    
    	//arr[i~j]的异或结果等于0,那么共有 j-i种结果
				count2 += j - i;
			}
		}
	}
	return count2;
}

That's it. If you are interested and want to communicate, you can leave a message to me.

Guess you like

Origin blog.csdn.net/h799710/article/details/106037847