我尝试查找在一个数组中出现奇数次的所有元素。我已经做了一些工作,但是我的代码只有在只有一个数字出现奇数次时才返回正确答案。如果有两个或更多的奇数出现数字,那么我就无法处理它。 我理解的是,如果我们对元素进行按位异或,那么我们会得到一个奇数出现的元素。如何改进它以处理多个数字?
以下是我的代码:
需要帮助解决这个问题!
以下是我的代码:
public class OddOccur {
public int oddoccurence(int[] arr, int size) {
int res = 0;
int[] fin = new int[size];
for (int i = 0; i < size; i++) {
res = res ^ arr[i];
}
return res;
}
public static void main(String args[]) {
int[] arr = { 2, 5, 5, 2, 2, 3, 3, 3 };
int n = arr.length;
OddOccur obj = new OddOccur();
System.out.println("odd occuring element is:"
+ obj.oddoccurence(arr, n));
}
}
需要帮助解决这个问题!
Map<Integer, Integer>
对于解决这个问题会更容易吗? - Kent