[ 问题: ]
Given an array of integers, every element appears twice except for one. Find that single one./** * Time Limit Exceeded * 时间复杂度为:O(n²),无法通过 */ public class Solution1 { public int singleNumber(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i] == arr[j]) { count++; } } if (count == 1) { return arr[i]; } else { count = 0; } } return -1; } public static void main(String[] args) { int[] arr = { 0, 1, 1, 2, 2, 3, 0 }; System.out.println(new Solution1().singleNumber(arr)); } }②. 标准解法:使用异或运算
/** * 利用异或的可交换性 */ public class Solution2 { public int singleNumber(int[] arr) { // invalid check if (arr.length == 0) { return -1; } int result = 0; for (int i = 0; i < arr.length; i++) { result = result ^ arr[i]; } return result; } public static void main(String[] args) { int[] arr = { 0, 1, 1, 2, 2, 3, 0 }; System.out.println(new Solution2().singleNumber(arr)); } }
异或运算的两个法则:
①. a ^ b = b ^ a
②. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c
真 ^ 假 = 真 假 ^ 真 = 真 假 ^ 假 = 假 真 ^ 真 = 假
/** * 不使用第三个变量,交换两个变量的值 */ public class Swap { public static void main(String[] args) { int a = 1, b = 2; System.out.println("交换前: a = " + a + " , b = " + b); a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("交换后: a = " + a + " , b = " + b); } }