我执行了下面的代码来打印出现奇数次的数组中的数字。但是这段代码打印数组的最后一个元素
I have executed the below code to print the number in an array which occurs odd number times. But this codes print the last element of the array
我认为问题出在“num = A[i]”这一行我试图将 num 分配为零。但是无法完成。
public static int solution(int A[]){
int num = A[0];
int count = 0;
for(int i = 0; i<A.length ; i++) {
for(int j = 0; j<A.length; j++) {
if(A[i] == A[j]) {
count++;
}
if(count%2 != 0)
num = A[i];
else
count = 0;
}
}
return num;
}
public static void main(String[] args) {
int arr[] = {10,22,345,22,345,10,5};
System.out.println(solution(arr));
}
您可以尝试这样的事情并跟踪多个解决方案:
Set<Integer> odds = new HashSet<Integer>();
for (int i : A) {
if (odds.contains(i)) {
odds.remove(i);
} else {
odds.add(i);
}
}
System.out.println(odds);
我认为问题出在“num = A[i]”这一行我试图将 num 分配为零。但是无法完成。
public static int solution(int A[]){
int num = A[0];
int count = 0;
for(int i = 0; i<A.length ; i++) {
for(int j = 0; j<A.length; j++) {
if(A[i] == A[j]) {
count++;
}
if(count%2 != 0)
num = A[i];
else
count = 0;
}
}
return num;
}
public static void main(String[] args) {
int arr[] = {10,22,345,22,345,10,5};
System.out.println(solution(arr));
}
您可以尝试这样的事情并跟踪多个解决方案:
Set<Integer> odds = new HashSet<Integer>();
for (int i : A) {
if (odds.contains(i)) {
odds.remove(i);
} else {
odds.add(i);
}
}
System.out.println(odds);