在数组中查找非重复元素

编程入门 行业动态 更新时间:2024-10-28 12:23:19
本文介绍了在数组中查找非重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我被困在以下程序中:

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

更多推荐

在数组中查找非重复元素

本文发布于:2023-11-22 00:57:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!