我是靠谱客的博主 震动水池,这篇文章主要介绍数组的异或和,现在分享给大家,希望可以做个参考。

定义数组的异或和的概念:
数组中所有的数异或起来,得到的结果叫做数组的异或和,比如数组{3,2,1}的异或和是,321 = 0
【题目】给定一个数组arr,你可以任意把arr分成很多不相容的子数组,你的目的是:分出来的子数组中,异或和为0的子数组最多。
请返回:分出来的子数组中,异或和为0的子数组最多是多少?

public class MostXOR {
public static int mostXOR(int[] arr) {
int ans = 0;
int xor = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int[] dp = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
xor ^= arr[i];
if (map.containsKey(xor)) {
int pre = map.get(xor);
dp[i] = pre == -1 ? 1 : dp[pre] + 1;
}
if (i > 0) {
dp[i] = Math.max(dp[i], dp[i - 1]);
}
map.put(xor, i);
ans = Math.max(ans, dp[i]);
}
return ans;
}
}

最后

以上就是震动水池最近收集整理的关于数组的异或和的全部内容,更多相关数组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部