题目
Given an array of integers, find the one that appears an odd number of times.There will always be only one integer that appears an odd number of times.
原题 给定一个整数数组,找出出现奇数次的整数。总是只有一个整数出现奇数次input : new int[]{20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5} output : 5
分析
我的解法
import java.util.Arrays;public class FindOdd {public static int findIt(int[] a) {Arrays.sort(a);for(int i = 0; i< a.length ;i++){if(i == a.length-1){return a[i];}else if (a[i] != a[++i] ){return a[--i];}}return 0;}}
参考解法
public class FindOdd {public static int findIt(int[] A) {int xor = 0;for (int i = 0; i < A.length; i++) {xor ^= A[i];}return xor;}}
提升
利用异或运算,相同的数字进行异或后等于0,0与任意数字进行异或运算都是该数字本身。
