本文介绍了在数组中查找非重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被困在以下程序中:
我有一个输入整数数组,只有一个非重复数字,比如{1,1,3,2, 3}。输出应该显示非重复元素,即2。
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
到目前为止,我做了以下内容:
So far I did the following:
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)); } }最好限制数组中的解决方案。避免使用集合,地图。
Restricting the solution in array is preferable. Avoid using collections,maps.
推荐答案因为这几乎肯定是一个学习练习,因为你非常接近完成它,以下是您需要更改以使其工作的内容:
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
- 移动的声明flag inside 外部循环 - 该标志需要设置为 true 每次外部迭代循环,它不会在外循环之外的任何地方使用。
- 当内循环完成时检查标志 - 如果标志仍为 true ,则表示您找到了唯一的编号;退货。
- Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
- Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
更多推荐
在数组中查找非重复元素
发布评论