且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到重复的重复数字

更新时间:2022-10-30 20:59:33

您可以在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 *** 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.