在数组中查找非重复元素

我被困在以下程序中:

我有一个输入整数数组,只有一个非重复数,比如{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)); } } 

限制arrays中的解决方案是优选的。 避免使用集合,地图。

因为这几乎肯定是一个学习练习,并且因为你非常接近完成它,所以你需要改变以使其工作:

  • 在外部循环中移动flag的声明在外部循环的每次迭代中都需要将标志设置为true ,并且不在外部循环之外的任何地方使用它。
  • 内循环完成时检查flag – 如果flag保持为true ,则找到唯一的数字; 把它返还。
 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); } } 
 From Above here is the none duplicated example in Apple swift 2.0 func noneDuplicated(){ let arr = [1,4,3,7,3] let size = arr.count var temp = 0 for i in 0.. 

我有一个独特的答案,它基本上采用你在数组的外部for循环中的当前数字,并自行计时(基本上是2的幂次数)。 然后它经历并且每次它看到数字不等于double本身测试如果它在内部for循环的数组的末尾,那么它就是一个唯一的数字,就好像它找到一个等于的数字它本身然后跳到内部for循环的末尾,因为我们已经知道一个数字不是唯一的。

 public class Solution { public int singleNumber(int[] arr){ int size = arr.length; int temp = 0; int result = 0; int temp2 = 0; int temp3 = 0; boolean flag = true; int[] arr1 = new int[size]; for(int i=0;i 

没有测试但应该工作

 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 

尝试:

 public class Answer{ public static void main(String[] args) { int[] a = {1,1,3,2,3}; int[] b =new int[a.length]; //instead of a.length initialize it to maximum element value in a; to avoid //ArrayIndexOutOfBoundsException for(int i=0;i 

PS:我对java很新,我通常用C编写代码。

谢谢@dasblinkenlight …按照你的方法

 public class Solution { public int singleNumber(int[] arr){ int size = arr.length; int temp = 0; int result = 0; int[] arr1 = new int[size]; for(int i=0;i 

一个灾难性的错误是没有将if(i != j)内容括在括号内。 谢谢大家的回答。

如果您正在为学习编码,那么您可以更有效地解决它。

  1. 使用合并排序快速排序对给定数组进行排序。 运行时间将是nlogn。
  2. 我们的想法是使用二进制搜索。 直到找到所需元素所有元素首先出现在偶数索引(0,2,…)和下一次出现在奇数索引(1,3,…)。 在必需元素首次出现在奇数索引和下一次出现在偶数索引之后。

使用上述观察,您可以解决:

a)找到中间指数,说’中’。

b)如果’mid’是偶数,则比较arr [mid]和arr [mid + 1]。 如果两者相同,那么在mid之前的’mid’之后所需的元素。

c)如果’mid’是奇数,那么比较arr [mid]和arr [mid-1]。 如果两者相同,那么在mid之前的’mid’之后所需的元素。

  /// for duplicate array static void duplicateItem(int[] a){ /* You can sort the array before you compare */ int temp =0; for(int i=0; i 
  /// for first non repeating element in array /// static void FirstNonDuplicateItem(int[] a){ /* You can sort the array before you compare */ int temp =0; for(int i=0; i