问题是:
给定一个非空数组的整数,除了一个以外,每个元素都出现两次。找到那个单独的。
输入: 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;
}我知道输出是4,现在它将被改为1。我正在尝试找出如何在找到后不更改找到的值。
发布于 2018-06-28 04:33:41
逻辑是错误的-您的内部循环查找数组中不是唯一数字的每个数字。
我会维护一个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();
}发布于 2018-06-28 05:09:23
对于这个问题,我会对数字进行逐位XOR运算。相等的数字将相互抵消,并且只有一个整数将是最终值。
public static int singleNumber(int[] nums) {
int answer = 0;
for (int i =0; i<nums.length; i++) {
answer = answer ^ nums[i];
}
return answer;
}发布于 2018-06-28 04:43:09
下面对您的方法所做的更改将为您提供预期的答案
public static int singleNumber(int[] nums) {
int temp = 0;
int answer = 0;
for (int i = 0; i < nums.length; i++) {
boolean flag = true;
temp = nums[i];
for (int j = 0; j < nums.length; j++) {
if (temp == nums[j]) {
if (i != j) {// if a match found then the loop will terminate
flag = false;
break;
}
}
}
if (flag == true) {
answer = temp;
}
}
return answer;
}https://stackoverflow.com/questions/51070885
复制相似问题