使用for循环和.搜索值

Jam*_*ang 4 java arrays loops for-loop unique

问题是:

给定一个非空的整数数组,除了一个元素外,每个元素都会出现两次.找一个单一的.

输入:[4,1,2,1,2]
输出:4

我的代码是:

public static int singleNumber(int[] nums) {
     int answer = 0;
        for (int i =0; i<nums.length-1; i++) {
            for(int j = i+1; j<nums.length; j++) {
                if(nums[i] != nums[j]) {
                 answer = nums[i];      //this should be where I am wrong.
                }
            }
        }
        return answer;
    }
Run Code Online (Sandbox Code Playgroud)

我知道输出是4然后现在它将被改为1.我试图找出如何在找到后不改变找到的值.

Mur*_*nik 8

逻辑是错误的 - 你的内部循环找到的每个数字都不是数组中唯一的数字.

我会保持Set跟踪我遇到的数字.第一次遇到号码时,将其添加到Set.第二次遇到它时,将其从中删除Set.一旦你完成了数组,你就会得到Set一个单独的元素,这是你的答案:

public static int singleNumber(int[] nums) {
    Set<Integer> unique = new HashSet<>();
    for (int num : nums) {
        // add returns true if num is indeed new to unique
        if (!unique.add(num)) {
            unique.remove(num);
        }
    }

    return unique.iterator().next();
}
Run Code Online (Sandbox Code Playgroud)