滴滴笔试题,异或性质的利用

给出n个数字 a_1,...,a_n,问最多有多少不重叠的非空区间,

使得每个区间内数字的xor都等于0

输入描述:

第一行一个整数n; 第二行n个整数 a_1,...,a_n 对于

30%的数据,n<=20 对于100%的数据,n<=100000,

a_i<=100000

输出描述:

一个整数表示最多的区间个数;

示例1

输入

4

3 0 2 2

输出

2

import java.util.HashMap;

public class Main {

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

	public static void main(String[] args) {
		int[] test = { 3, 0, 2, 2 };
		System.out.println(mostXORs0(test));
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值