c++ - 从数组中删除非唯一值,保持顺序且不使用 vector 的最佳方法?

标签 c++ sorting

如果有人提出这个问题,我深表歉意,但我遇到了一个编码问题,该问题本来很简单,但我一直在努力。如果已经回答,请提供链接(我可能搜索不好)。

问题:给定示例代码,请填写函数以仅返回数组中的唯一值。值必须保持秩序。

输入示例:1、2、3、10、4、3、2、10、1、11、6

示例输出:1 2 3 10 4 11 6

以下是我的解决方案,但我似乎无法想到一个不包含使用 vector 存储唯一值的简单解决方案。测试人员不喜欢使用 vector ,因此我只能假定其他 header /库是 Not Acceptable 。还有其他解决方案吗?我猜测试人员正在寻找要过滤的数组。

#include <iostream>
#include <vector> //I was not allowed to add this...

//Function to fill in...
int fxn(int *a, int size)
{
  std::vector<int> temp;
  for(int i(0); i < size; ++i)
  {
    bool found(false);
    for(auto j : temp)
    {
      if( j == a[i])
      {
        found = true;
        break;
      }
    }

    if(!found)
    {
      temp.push_back(a[i]);
    }
  }

  int *ptr_a = &a[0];
  for(auto j : temp)
  {
    *ptr_a = j;
    ++ptr_a;
  }

  return size - temp.size();
}

//The rest untochable...
void print(int *a, int size)
{
  for(int i(0); i < size; ++i)
  {
    std::cout << a[i] << " ";
  }

  std::cout << std::endl;
}

int main(void)
{

  int a[] = { 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6 };
  int size = 11;

  int count = fxn(a, size);
  print(a, size - count);

  return 0;
}

最佳答案

诚然,如果您可以使用外部库,则此问题会更容易,但是如果确定不能,则仍然可以解决。

我是第一次错误地读了这个问题。 Here是指向类似问题的链接。

#include<iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    int j = 0;

    for (int i=0; i < n; i++){
        for(int j=0;j<i;j++){

            if(arr[i]==arr[j]){
                n--;
                for (int k=i; k<n; k++){
                    arr[k]=arr[k+1];
                }
                i--;     // you forgot to decrement i
            }
        }
    }

    return n;
}

关于c++ - 从数组中删除非唯一值,保持顺序且不使用 vector 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62090991/

相关文章:

c++ - 在c++中添加两个c字符串

python - 在 Python 中按不同级别排序

python - 如何使用 BeautifulSoup 4 按子元素对无序列表进行排序

c++ - 无法使用 read() 将文件内容读入缓冲区

c++ - 从 char(不是 char*)到 std::string 的首选转换

c++ - 具有多个指针的 Pimpl

c++ - 如何在 C++ 中使用 [] 运算符获取对象

arrays - 我将如何快速对数组中的项目进行分类?

linux - Bash 用 * 数字枚举文件

sorting - Thrust::sort 有多快以及最快的基数排序实现是什么