求数组中唯一奇数次出现的数

主题:面经

题目:

An array of integers, only one integer appears odd times, all others appear even times, find it


Code:

import java.util.*;

class Test{
    public static void main(String[] args){
		Solution sol = new Solution();
		int[] A = {1, 2, 2, 3, 3, 1, 4, 4, 4, 4, 0, 0, 1};
		System.out.println(sol.xorOdd(A));
		System.out.println(sol.getOdd(A));
    }
}

class Solution{
	//XOR法
	public int xorOdd(int[] A){
		if(A==null || A.length==0) return Integer.MIN_VALUE;
		int res = 0;
		for(int i=0; i<A.length; i++)
			res ^= A[i];
		return res;
	}
	
	//Hashing法
	public int getOdd(int[] A){
		if(A==null || A.length==0) return Integer.MIN_VALUE;
		HashMap<Integer, Boolean> hm = new HashMap<Integer, Boolean>();
		for(int i=0; i<A.length; i++){
			if(hm.containsKey(A[i])) hm.put(A[i], !hm.get(A[i]));
			else hm.put(A[i], true);
		}
		for(int key : hm.keySet())
			if(hm.get(key)) return key;
		return Integer.MIN_VALUE;
	}
}


小结:

Hashing方法自不必说,O(n)的时间和空间复杂度。

XOR的方法,引用一段career-cup上的话:

XOR of a number with itself will give you a 0. 0 XOR'd with any number will give you the same number. Thus an even count of a particular number will give you a 0 while an odd count will give you the number itself. 
If you XOR all values one after the other, the even count values will cancel each other out and only the odd count value will remain at the end.

大意是说:0和任何数的XOR都是数本身;数和自己本身的XOR为0。利用这个原理,唯一的一个奇数次出现的数肯定会在一次遍历过后留下,赞!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值