1442:形成两个异或相等数组的三元组数目

This commit is contained in:
huangge1199 2021-05-18 13:06:51 +08:00
parent 2f8a03ef4b
commit 382d30f13d
3 changed files with 146 additions and 1 deletions

View File

@ -0,0 +1,88 @@
//给你一个整数数组 arr
//
// 现需要从数组中取三个下标 ij 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) 的数目
//
//
//
// 示例 1
//
// 输入arr = [2,3,1,6,7]
//输出4
//解释满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)
//
//
// 示例 2
//
// 输入arr = [1,1,1,1,1]
//输出10
//
//
// 示例 3
//
// 输入arr = [2,3]
//输出0
//
//
// 示例 4
//
// 输入arr = [1,3,5,7,9]
//输出3
//
//
// 示例 5
//
// 输入arr = [7,11,12,9,5,2,7,17,22]
//输出8
//
//
//
//
// 提示
//
//
// 1 <= arr.length <= 300
// 1 <= arr[i] <= 10^8
//
// Related Topics 位运算 数组 数学
// 👍 105 👎 0
package leetcode.editor.cn;
//1442:形成两个异或相等数组的三元组数目
public class CountTripletsThatCanFormTwoArraysOfEqualXor {
public static void main(String[] args) {
//测试代码
Solution solution = new CountTripletsThatCanFormTwoArraysOfEqualXor().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int countTriplets(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
int xor = arr[i];
for (int j = i + 1; j < arr.length; j++) {
xor ^= arr[j];
if (xor == 0) {
count += j - i;
}
}
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,57 @@
<p>给你一个整数数组 <code>arr</code></p>
<p>现需要从数组中取三个下标 <code>i</code><code>j</code><code>k</code> ,其中 <code>(0 &lt;= i &lt; j &lt;= k &lt; arr.length)</code></p>
<p><code>a</code><code>b</code> 定义如下:</p>
<ul>
<li><code>a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]</code></li>
<li><code>b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]</code></li>
</ul>
<p>注意:<strong>^</strong> 表示 <strong>按位异或</strong> 操作。</p>
<p>请返回能够令 <code>a == b</code> 成立的三元组 (<code>i</code>, <code>j</code> , <code>k</code>) 的数目。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入:</strong>arr = [2,3,1,6,7]
<strong>输出:</strong>4
<strong>解释:</strong>满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)
</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入:</strong>arr = [1,1,1,1,1]
<strong>输出:</strong>10
</pre>
<p><strong>示例 3</strong></p>
<pre><strong>输入:</strong>arr = [2,3]
<strong>输出:</strong>0
</pre>
<p><strong>示例 4</strong></p>
<pre><strong>输入:</strong>arr = [1,3,5,7,9]
<strong>输出:</strong>3
</pre>
<p><strong>示例 5</strong></p>
<pre><strong>输入:</strong>arr = [7,11,12,9,5,2,7,17,22]
<strong>输出:</strong>8
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= arr.length &lt;= 300</code></li>
<li><code>1 &lt;= arr[i] &lt;= 10^8</code></li>
</ul>
<div><div>Related Topics</div><div><li>位运算</li><li>数组</li><li>数学</li></div></div>\n<div><li>👍 105</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long