Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
import java.util.*; import java.util.Map.*; public class Solution { public int singleNumber(int[] A) { /* HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<A.length;i++){ if(map.get(A[i])==null) map.put(A[i],1); else map.put(A[i],map.get(A[i])+1); } for(Entry<Integer,Integer> entry:map.entrySet()){ int a=entry.getValue(); int k=entry.getKey(); if(a==1) return k; } return 0; */ //使用异或,两个二进制数异或,相同就会为0,不同的为1。所以两个相同整数异或为0,而所有整数与0异或还是这个整数本身 int result=A[0]; for(int i=1;i<A.length;i++) result^=A[i]; return result; } }