天涯尽头无女友
最好的答案是XOR运算符。只是为了好玩,如果允许对数组进行排序,可以对它进行排序并比较相邻的整数。假定所有整数恰好出现两次,一个整数出现一次。// Random array of integersint[] arr = {1, 2, 3, 4, 5, 6, 7, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9};// Sort the array.Arrays.sort(arr);// Array now looks like: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 9 9 // Cycle through array comparing adjacent values.for(int i = 0; i < arr.length; i++){ // This would mean the single number was the last element in the array. if(i == arr.length-1) singleNum = arr[i]; // If the adjacent elements are the same, skip foward. if(i < arr.length-1 && arr[i] == arr[i+1]) i ++; else // Otherwise, you found the single number. singleNum = arr[i];}