在C ++中过滤掉数组中的重复值

时间:2017-11-24 09:05:15

标签: c++ arrays loops duplicates

我有一行十个数字,例如:

  

5 5 6 7 5 9 4 2 2 7

现在我想要一个找到所有重复项目的程序,并在控制台中将它们分出3次5次,2次2次,2次7次。 虽然我编写了一个算法,可以在一行数字中找到重复项,但我无法按照描述在控制台中将它们输出。我的程序将输出:

3 times 5
2 times 5
2 times 7
2 times 2

我该如何解决这个问题?

#include <iostream>

using namespace std;

int main()
{
  int arr[10];
  int i,j;
  int z = 1;

    for(i = 0; i < 10; i++) {
        cin >> arr[i];
    }
    for(i = 0; i < 10; i++){
        for(j = i+1; j < 10; j++){
            if(arr[i] == arr[j]){
                z++;
            }
        }
        if(z >= 2){
        cout << z << " times " << arr[i] << endl;
        z = 1;
        }

    }


    return 0;
}

4 个答案:

答案 0 :(得分:0)

您需要检查之前是否找不到arr[i],例如:

if(z >= 2) {
    int found_before = 0;
    for(j = 0; j < i; ++j)
        if(arr[i] == arr[j])
            found_before = 1;
    if(!found_before)
        cout << z << " times " << arr[i] << endl;
    z = 1;
}

将打印:

3 times 5
2 times 7
2 times 2

这样您就不会再次打印5

使用你的代码,它会打印出它发现5次(对于数组中的前5个),然后当它移动到数组中的第5个时,它会忘记数组中的前5个,并报告它发现了5次(本身和数组的第5个数字)。

答案 1 :(得分:0)

一种简单的方法是为它创建另一个数组,特别是如果数字不是那么大。

假设您已初始化数组:int nums[10] = { 5, 5, 6, 7, 5, 9, 4, 2, 2, 7 }

int result[max(nums)]; //Fill with zeroes, max(nums) is the highest number in the array
for(int i = 0; i < 10; i++) {
    result[nums[i]]++;
}

for(int i = 0; i < max(nums); i++) {
    if (result[i] > 1) cout << result[i];
}

请注意,这并未针对内存进行优化。对于较大数量的内容,您可能需要考虑哈希映射。

答案 2 :(得分:0)

为什么保持算法的想法,我建议创建子方法:

std::size_t count(const int* arr, std::size_t start, std::size_t end, int value)
{
    std::size_t res = 0;
    for (std::size_t i = start; i != end; ++i) {
        if (arr[i] == value) {
            ++res;
        }
    }
    return res;
}

然后您的固定算法将是:

for (std::size_t i = 0; i != 10; ++i) {
    if (count(arr, 0, i, arr[i]) != 0) {
        continue; // Already visited
    }
    auto total = count(arr, i, 10, arr[i]);
    if(total >= 2){
        std::cout << z << " times " << arr[i] << std::endl;
    }
}

答案 3 :(得分:0)

如果你不需要性能而是紧凑的代码,那么std :: multiset与std :: upper_bound是另一种选择:

#include<set>
#include<iostream>
#include<algorithm>

int main(int a, char** b)
{
  int array[] = {5, 5, 6, 7, 5, 9, 4, 2, 2, 7};

  std::multiset<int> a(std::begin(array), std::end(array));
  for(auto it = a.begin(); it != a.end(); it = std::upper_bound(a.begin(), a.end(), *it))
  {
    if(a.count(*it) > 1)
        std::cout << *it << " times " << a.count(*it) << std::endl;
  }

  return 0;
}
相关问题