本文介绍了找到重复的重复数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的算法,我已经和我的朋友(这是在stackoverflow网站)中写的这个算法将只找到第一个重复的数字并返回它。这个工作在
O( n)
我想完成这个算法,帮助我重复一次重复的数字。认为我有
[1,1,3,0,5,1,5]
我想要这个算法返回
2
重复数字,分别为 1和5
,其重复次数分别为 3和2
我可以用 O(n)
吗? 1算法重复(arr [1:n],n)
2
3 {
4 Set s = new HashSet(); i:= 0;
5而i< a.size()do
6 {
7 if(!s.add(a [i))then
8 {
9 return a [i] //这是一个重复的值!
10休息;
11}
12 i ++;
13}
14}
解决方案
您可以在Java中执行此操作:
列表<整数> num = Arrays.asList(1,1,1,2,3,3,4,5,5,5);
映射<整数,整数> countNum = new HashMap< Integer,Integer>();
(int n:num)
{
整数nu;
if((nu = countNum.get(n))== null)
{
countNum.put(n,1);
继续;
}
countNum.put(n,nu + 1);
}
而不是每次迭代得到重复的数量,最好存储计数在地图上。
this is my algorithm that I have written it with my friends (which are in stackoverflow site)this algorithm will find just the first duplicate number and returns it.this works in O(n)
I want to complete this algorithm that helps me to get duplicate numbers with their repetition. consider that I have [1,1,3,0,5,1,5]
I want this algorithm to return 2
duplicate numbers which are 1 and 5
with their repetition which is 3 and 2
respectively .how can I do this with O(n)
?
1 Algorithm Duplicate(arr[1:n],n)
2
3 {
4 Set s = new HashSet();i:=0;
5 while i<a.size() do
6 {
7 if(!s.add(a[i)) then
8 {
9 return a[i]; //this is a duplicate value!
10 break;
11 }
12 i++;
13 }
14 }
解决方案
You can do this in Java:
List<Integer> num=Arrays.asList(1,1,1,2,3,3,4,5,5,5);
Map<Integer,Integer> countNum=new HashMap<Integer, Integer>();
for(int n:num)
{
Integer nu;
if((nu=countNum.get(n))==null)
{
countNum.put(n,1);
continue;
}
countNum.put(n,nu+1);
}
Instead of iterating each time to get count of duplicate it's better to store the count in map.
这篇关于找到重复的重复数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!