我卡在了下面的程序中:
我有一个输入整数数组,它只有一个不重复的数字,比如 {1,1,3,2,3}。输出应显示非重复元素,即 2。
到目前为止,我做了以下事情:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
最好将解决方案限制在数组中。避免使用集合、 map 。
最佳答案
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
关于java - 查找数组中的非重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27722009/