[英]Find the first non repeating integers of array
This program is giving output for all non-repeated elements but I need first one non-repeated element.该程序为所有非重复元素提供输出,但我首先需要一个非重复元素。 I tried to keep
if(flag==1)
to break loop after the end of j loop, then I tested but it is not working for all cases我试图保持
if(flag==1)
在 j 循环结束后中断循环,然后我进行了测试,但它不适用于所有情况
import java.util.Scanner;
public class first
{
public static void main(String[] args)
{
int n, flag = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Non repeated first element is :");
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i != j)
{
if(a[i]!= a[j])
{
flag = 1;
}
else
{
flag = 0;
break;
}
if(flag == 1)
{
System.out.print(" ");
System.out.println(a[i]);
break;
}
}
}
}
}
}
You can construct two sets, singleSet
and repeatedSet
, respectively for elements appeared once and more than once.您可以分别为出现一次和
repeatedSet
的元素构造两个集合, singleSet
和repeatedSet
集。 They can be created by doing one iteration on elements.它们可以通过对元素进行一次迭代来创建。 Then, you do an a second iteration, to query which is the first element non-repeated:
然后,您进行第二次迭代,以查询哪个是非重复的第一个元素:
int[] elements = { 1, 1, 2, 3, 3, 4 };
Set<Integer> singleSet = new HashSet<>();
Set<Integer> repeatedSet = new HashSet<>();
for (int e : elements) {
if (repeatedSet.contains(e)) {
continue;
}
if (singleSet.contains(e)) {
singleSet.remove(e);
repeatedSet.add(e);
} else {
singleSet.add(e);
}
}
for (int e : elements) {
if (singleSet.contains(e)) {
return e;
}
}
This solution is a O(n)
solution, it should be faster than the nested-loop, which is O(n^2)
.这个解决方案是一个
O(n)
解决方案,它应该比嵌套循环更快,它是O(n^2)
。
You can also replace the singeSet
by a singleList
, and at the end, return the first element in the singleList
, which avoid the 2nd iteration on elements.您还可以将
singeSet
替换为singleList
,最后返回singleList
的第一个元素,从而避免对元素进行第二次迭代。 Thus the solution is even faster.因此,解决方案甚至更快。
Following up on the idea of the two sets from @Mincong , I am adding here the solution he mentioned as faster.跟进@Mincong 的两组想法,我在这里添加了他提到的更快的解决方案。
int[] array = { 1, 1, 2, 3, 3, 4 };
Set<Integer> allValues = new HashSet<>(array.length);
Set<Integer> uniqueValues = new LinkedHashSet<>(array.length);
for (int value : array) {
if (allValues.add(value)) {
uniqueValues.add(value);
}
else {
uniqueValues.remove(value);
}
}
if (!uniqueValues.isEmpty()) {
return uniqueValues.iterator().next();
}
def non_repeating(arr):
non_repeating = []
for n in arr:
if n in non_repeating:
non_repeating.pop(non_repeating.index(n))
else:
non_repeating.append(n)
return non_repeating[0] if non_repeating else None
print(non_repeating([1, 1, 1, 5, 2, 1, 3, 4, 2]))
def solution(self, list):
count_map = {}
for item in list:
count_map[item] = count_map.get(item, 0) + 1
for item in list:
if count_map[item] == 1:
return item
return None
Here is a python code trying to achieve the same -这是一个试图实现相同目标的python代码-
def singleNumber(nums: List[int]) -> int:
from collections import defaultdict
memory = defaultdict(int)
for num in nums:
memory[num] += 1
for k,v in memory.items():
if v == 1:
return k
Javascript Javascript
function nonRepeatinInteger(arr) {
let val = [], count = [];
arr.forEach((item, pos) => {
if (!val.includes(item)) {
val.push(item);
count[val.indexOf(item)] = 1;
} else {
count[val.indexOf(item)]++;
}
});
return val[count.indexOf(Math.min(...count))];
}
console.log(nonRepeat([-1, 2, -1, 3, 2]));
console.log(nonRepeat([9, 4, 9, 6, 7, 4]));
private int getFirstNonRepeating(int[] arr) {
Set<Integer> set = new HashSet<>();
ArrayList<Integer> list = new ArrayList<>();
int min = 0;
for (int i = 0; i <arr.length; i++) {
//Parsing though array and adding to list if set.add returns false it means value is already available in set
if (!set.add(arr[i])) {
list.add(arr[i]);
}
}
//Parsing though array and checking if each element is not available in set,then that is smallest number
for (int i = 0; i < arr.length; i++) {
if (!list.contains(arr[i])) {
min = arr[i];
break;
}
}
Log.e(TAG, "firstNonRepeating: called===" + min);
return min;
}
Try this :试试这个:
int a[] = {1,2,3,4,5,1,2};
for(int i=0; i<a.length;i++) {
int count = 0;
for(int j=0; j<a.length;j++) {
if(a[i]==a[j] && i!=j) {
count++;
break;
}
}
if(count == 0) {
System.out.println(a[i]);
break; //To display first non repeating element
}
}
Using JS Object:使用 JS 对象:
function nonRepeat_Using_Object(arr) {
const data = arr.reduce((acc, val) => {
if (!acc[val]) {
acc[val] = 0;
}
acc[val]++;
return acc;
}, {});
for (let i = 0; i < arr.length; i++) {
if (data[arr[i]] === 1) {
return arr[i];
}
}
}
实现此目的的另一种方法:您可以使用哈希图在第一次传递中存储整数计数,并在第二次传递中返回计数为 1 的第一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.