寻找独特数字卡片问题解析 | 豆包MarsCode AI刷题

59 阅读1分钟

寻找独特数字卡片问题解析

在这个问题中,我们需要找到在一个数组中唯一一个只出现一次的数字,而其余数字都恰好出现了两次。题目明确给出了几个重要的约束条件,包括数组长度为奇数、每个元素的范围、以及除了一个数字之外其他数字都恰好成对出现。这些条件帮助我们设计高效的算法来解决这个问题。

public class Main {
    public static int solution(int[] inp) {
        int uniqueNumber = 0; // 初始化一个变量来存储最终的结果
        for (int num : inp) { // 遍历输入的数组
            uniqueNumber ^= num; // 对每个数字进行异或操作
        }
        return uniqueNumber; // 返回最终找到的单独数字
    }

    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);
    }
}