问题描述:在一个班级中,每位同学都拿到了一张卡片,上面有一个整数。有趣的是,除了一个数字之外,所有的数字都恰好出现了两次。现在需要你帮助班长小C快速找到那个拿了独特数字卡片的同学手上的数字是什么。 要求: 1.设计一个算法,使其时间复杂度为 O(n),其中 n 是班级的人数。 2.尽量减少额外空间的使用,以体现你的算法优化能力。
完整代码: public class Main { public static int solution(int[] cards) { // 初始化结果为0 int result = 0;
// 遍历数组中的每个数字
for (int number : cards) {
// 对每个数字进行异或运算
result ^= number;
}
// 返回结果
return result;
}
public static void main(String[] args) {
// 测试用例
System.out.println(solution(new int[]{1, 1, 2, 2, 3, 3, 4, 5, 5}) == 4);
System.out.println(solution(new int[]{0, 1, 0, 1, 2}) == 2);
System.out.println(solution(new int[]{7, 3, 3, 7, 10}) == 10);
}
} 初始化结果变量 int result = 0; 需要一点思路提示
好的,让我们一起来分析这个问题。
问题理解
我们需要在一个整数数组中找到唯一一个出现一次的数字。数组中的其他数字都恰好出现两次。
数据结构选择
由于题目要求时间复杂度为 O(n),并且尽量减少额外空间的使用,我们可以考虑使用位运算来解决这个问题。
算法步骤
-
异或运算:异或运算有一个重要的性质,即对于任何整数 x:
x ^ x = 0(任何数与自身异或结果为0)x ^ 0 = x(任何数与0异或结果为自身)
-
利用异或运算的性质:我们可以遍历整个数组,将所有元素进行异或运算。由于相同的数字异或结果为0,最终剩下的就是那个唯一的数字。
伪代码
result = 0
for each number in cards:
result = result ^ number
return result
代码框架
可以根据上述思路在代码中实现:
public class Main {
public static int solution(int[] cards) {
// 初始化结果为0
int result = 0;
// 遍历数组中的每个数字
for (int number : cards) {
// 对每个数字进行异或运算
result ^= number;
}
// 返回结果
return result;
}
public static void main(String[] args) {
// 测试用例
System.out.println(solution(new int[]{1, 1, 2, 2, 3, 3, 4, 5, 5}) == 4);
System.out.println(solution(new int[]{0, 1, 0, 1, 2}) == 2);
System.out.println(solution(new int[]{7, 3, 3, 7, 10}) == 10);
}
}
### 总结
通过使用异或运算,我们可以在 O(n) 的时间复杂度内找到唯一的数字,并且不需要额外的空间。