题目:一个整型数组里除了两个数字外,其他的数字都出现了两次,请写一个程序找出只出现一次的数字,要求时间复杂度O(n),空间复杂度O(1)
算法:首先对所有数字取异或,找到结果中有一位不为0的位置,然后,对所有元素分组,分为两个部分;然后对每个部分分别取异或
import java.util.*; public class Main21 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; int[] numb; while (scanner.hasNext()) { n = scanner.nextInt(); numb = new int[n]; for (int i = 0; i < n; i++) { numb[i] = scanner.nextInt(); } int value = 0; for (int i = 0; i < n; i++) { value ^= numb[i]; } int index = 0; while (((value & 1) == 0) && (index < 32)) { value = value >> 1; index++; } int num1 = 0, num2 = 0; for (int i = 0; i < n; i++) { value = numb[i] >> index; if ((value & 1) == 0) { num1 ^= numb[i]; } else { num2 ^= numb[i]; } } System.out.println(num1); System.out.println(num2); } } }