【问题标题】:Count how many times elements in an array are repeated计算数组中元素重复的次数
【发布时间】:2016-04-21 14:10:10
【问题描述】:

我正在尝试编写的程序允许我输入 10 个数字,它应该会告诉我数字 X 重复 X 次,依此类推。

我一直在尝试这个,但问题是我得到的结果如下:

例如...{1,1,1,1,4,6,4,7,4}

数字1重复4次

数字1重复3次

数字1重复2次

数字1重复1次

数字4重复3次

数字6重复1次

数字 4 重复了 2 次​​p>

数字 7 重复 1 次

数字4重复1次

问题是它用后面的数字检查下一个数字而不跳过它,或者不知道它之前写过它

#include <iostream>
#include <string>
using namespace std;
int main() {
    int x[10];
    for (int i=0;i<10;i++) {
        cin>>x[i];
    }

    for (int i=0;i<9;i++) {
        int count=1;
        for (int j=i+1;j<10;j++) { 
            if (x[i]==x[j]) count++;
        }
        cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
    }
}

【问题讨论】:

  • 提示:尝试使用std::map&lt;int, int&gt;
  • 作为另一个提示,在您的程序中有两个循环:一个用于读取内容,另一个用于报告计数。
  • 已经有2个循环了!!! for (int i=0;i

标签: c++


【解决方案1】:

您的代码的问题在于您重新处理了已经处理过的数字。因此,如果在位置 0 出现 1,在位置 5 出现另一个 1,那么当您进入循环时,您将在位置 5 再次处理 1

因此,您需要一种方法来确定某个号码是否已被处理。一种简单的方法是添加第二个数组(最初所有值都设置为 0),并且每当您处理一个数字时,您都会标记该元素出现的所有位置。现在在处理一个元素之前,你检查它是否已经被处理过,如果是这样,什么也不做。

另外,尝试正确缩进你的代码:)

C++ 代码:

int main( void ) {
    const int N = 10;

    int A[N];
    for(int i = 0; i < N; i++)
        cin >> A[i];

    int seen[N];
    for(int i = 0; i < N; i++)
        seen[i] = 0;

    for(int i = 0; i < N; i++) {
        if(seen[i] == 0) {
            int count = 0;
            for(int j = i; j < N; j++)
                if(A[j] == A[i]) {
                    count += 1;
                    seen[j] = 1;
                }
            cout << A[i] << " occurs " << count << " times" << endl;
        }
    }

    return 0;
}

【讨论】:

  • 感谢我的朋友
【解决方案2】:

这是一个使用std::map 的相当简单的实现。

#include <map>
#include <vector>
#include <cstdlib>
#include <iostream>

std::map<int, unsigned int> counter(const std::vector<int>& vals) {
    std::map<int, unsigned int> rv;
    
    for (auto val = vals.begin(); val != vals.end(); ++val) {
        rv[*val]++;
    }

    return rv;
}

void display(const std::map<int, unsigned int>& counts) {
    for (auto count = counts.begin(); count != counts.end(); ++count) {
        std::cout << "Value " << count->first << " has count "
                  << count->second << std::endl;
    }
}

int main(int argc, char** argv) {
    std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
    display(counter(mem));
    
    return 0;
}

输出:

Value 1 has count 4
Value 4 has count 3
Value 6 has count 1
Value 7 has count 1

使用 C++14 标准编译,但它也应该适用于 C++11。去掉向量初始化器并使用auto,它应该适用于C++98。

更新:

我已经稍微更新了这段代码以使用std::unordered_map 而不是std::map,因为顺序似乎不是问题。此外,我还根据一些较新的 C++ 特性简化了循环控制。

#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <iostream>

std::unordered_map<int, unsigned int> counter(const std::vector<int>& vals) {
    std::unordered_map<int, unsigned int> rv;

    for (auto val : vals) {
        rv[val]++;
    }

    return rv;
}

void display(const std::unordered_map<int, unsigned int>& counts) {
    for (auto count : counts) {
        std::cout << "Value " << count.first << " has count " << count.second << std::endl;
    }
}

int main(int argc, char** argv) {
    std::vector<int> mem = {1, 1, 1, 1, 4, 6, 4, 7, 4};
    display(counter(mem));

    return 0;
}

输出:

Value 7 has count 1
Value 6 has count 1
Value 4 has count 3
Value 1 has count 4

在这种情况下,计数的顺序将是随机的,因为 std::unordered_map 是一个没有内在顺序的哈希表。

【讨论】:

  • 很棒的例子。
【解决方案3】:

我最近遇到的最有效的方法...

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
int array[10]={1,1,1,1,4,6,4,7,4};
int a[100];
memset(a,0,sizeof(a));
for(int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
    a[array[i]]++;
}
for(int i=1; i<sizeof(a)/sizeof(a[0]); i++)
{
    if(a[i]>0)
    {
        cout<<"The number "<<i<<"is repeated "<<a[i]<<" times"<<"\n";
    }

}

输出:

The number 1 is repeated 4 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 1 times

【讨论】:

    【解决方案4】:

    使用map 非常简单!

    Repl.it

    #include <iostream>
    #include <map>
    
    int main()
    {
        int foo[]{1,1,1,1,4,6,4,7,4};
        std::map<int, int> bar;
    
        for (auto const &f : foo)
            bar[f]++;
    
        for (auto const &b : bar)
            std::cout << "The number " << b.first 
                      << "is repeated " << b.second 
                      << "times\n";
    }
    

    预期输出:

    The number 1 is repeated 4 times
    The number 4 is repeated 3 times
    The number 6 is repeated 1 times
    The number 7 is repeated 1 times
    

    【讨论】:

      【解决方案5】:
      #include<iostream>
      #include<bits/stdc++.h>
      using namespace std;
      int main()
      {
          int n;
          cout<<"enter length of array:"<<endl;
          cin>>n;
          int arr[n];
          for(int i=0;i<n;i++)
          {
              cout<<"enter element:";
              cin>>arr[i];
      
          }
          sort(arr,arr+n);
          /*this is for sort the array so we can find maximum element form user input and 
         using this element we make one array of that size
         */
          int m=arr[n-1];
          m++;
          int a[m];
      
      
          for(int i=0;i<m;i++)
          {
              a[i]=0;
          }
      
          for(int i=0;i<n;i++)
          {
      
           a[arr[i]]++;
          }
         cout<<endl;
              for(int i=0;i<m;i++)
              {
                  if(a[i]>0)
                      cout<<i<<"is repeat:"<<a[i]<<"time"<<endl;
      
      
              }
      
      
      }
      

      输出是这样的:

      输入数组长度:

      6

      输入元素:6

      输入元素:5

      输入元素:5

      输入元素:6

      输入元素:2

      输入元素:3

      2是重复:1次

      3是重复:1次

      5是重复:2次

      6是重复:2次

      【讨论】:

        【解决方案6】:
        package DP;
        
        import java.util.Arrays;
        import java.util.HashMap;
        import java.util.Map;
        import java.util.TreeMap;
        
        public class countsofRepeatedNumber {
        
            public static void main(String[] args) {
                // TODO Auto-generated method stub
        
                int arr[]= {1,1,1,1,4,4,6,4,7};
                int n=arr.length;
                countNumber(arr,n);
            }
            
            private static void countNumber(int[] arr, int n) {
                TreeMap<Integer,Integer>list= new TreeMap<Integer,Integer>();
                
                 Arrays.sort(arr);
                 int count=1;
                 for(int i=0;i<n-1;i++) {
                    
                     if(arr[i]==arr[i+1]) {
                         count++;
                     }else {
                         list.put(arr[i], count);
                         count=1; 
                     }
                     
                    
                 }
                 list.put(arr[n-1], count);
                 
                 printDatas(list);
                 
            }
            
            private static void printDatas(TreeMap<Integer, Integer> list) {
                for(Map.Entry<Integer, Integer>m:list.entrySet()) {
                    System.out.println("Item "+m.getKey()+": "+m.getValue());
                }
            }
        
        }
        

        【讨论】:

          【解决方案7】:

          #include 使用命名空间标准; int重复(int a[],int n){ int i;诠释 c=1; for(i=0;i1) cout>t;而(t--){ int n;辛>>n;整数 [n]; for(int i=0;i>a[i];排序(a,a+n);重复(a,n); } }

          【讨论】:

          • 为什么同一件事发了两次?您可以随时edit您的答案。
          • 社区鼓励在代码旁边添加解释,而不是纯粹基于代码的答案(请参阅here)。另外,请查看formatting help page 以改进您的格式。
          【解决方案8】:

          这段代码在 O(n) 时间和 O(1) 空间内

          #include 使用命名空间标准; int重复(int a[],int n){ int i;诠释 c=1; for(i=0;i1) cout>t;而(t--){ int n;辛>>n;整数 [n]; for(int i=0;i>a[i];排序(a,a+n);重复(a,n); } }

          【讨论】:

          • 你为什么把同样的东西发了两次?您可以随时edit您的答案。
          • 社区鼓励在代码旁边添加解释,而不是纯粹基于代码的答案(请参阅here)。另外,请查看formatting help page 以改进您的格式。
          【解决方案9】:
              #include <iostream>
              #include<map>
              using namespace std;
              int main()
              {
                     int arr[]={1,1,1,1,4,6,4,7,4};
                     int count=1;
                     map<int,int> mymap;
                     try
                     {
                         if(sizeof(arr)/sizeof(arr[0])<=1)
                         {
                            throw 1;
                         }
                     }
                     catch(int x)
                     {
                         cout<<"array size is not be 1";
                         return 0;
                     }
                     
                     for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++)
                     {
                             for(int j=i;j<(sizeof(arr)/sizeof(arr[0]));j++)
                             {
                                 if(arr[i]==arr[j+1])
                                 {
                                     count++;
                                 }
                             }
                             
                             if(mymap.find(arr[i])!=mymap.end())
                             {
                                 auto it = mymap.find(arr[i]);
                                 if((it)->second<=count)
                                  (it)->second=count;
                                 count=1;
                             }
                             else if(count)
                             {
                                mymap.insert(pair<int,int>(arr[i],count));
                                count=1;
                             }
                     }
                    
                     for(auto it=mymap.begin();it!=mymap.end();it++)
                     {
                         cout<<it->first<<"->"<<it->second<<endl;
                     }
                  
                  return 0;
              }
          

          预期输出:

          1->4                                                                                                                             
          4->3                                                                                                                             
          6->1                                                                                                                             
          7->1
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-12-01
            • 1970-01-01
            • 2012-06-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多