从数组中删除非唯一性值,保持顺序且不使用向量的最佳方法?

问题描述 投票:1回答:1

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

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

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

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

下面是我的解决方案,但我似乎无法想到一个不包含使用向量存储唯一值的简单解决方案。测试人员不喜欢使用向量,因此我只能假定其他标头/库是不可接受的。还有其他解决方案吗?我猜测测试人员正在寻找要过滤的阵列。

#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;
}
c++ sorting
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.