0

我想返回数组中的第一个(第一次见面,从左到右)非重复元素。

我提供了一种算法,该算法很容易返回在数组中不重复的最小整数,仅使用数组作为额外空间,长度为数组中的最大整数值:

// smallest non repeating integer

int firstNonRepeatingInteger(int* input, int n)
{

     max = std::numeric_limits<int>::min() ;

     for(int i = 0 ; i < n ; i++)
     {
        if(input[i] > max)  
            max = input[i];
     }

     int* count = new int[max];

     for(int i = 0 ; i < n ; i++)
          count[input[i]] += 1 ;

     int j = 0;
     while(count[i] != 1)
       j++ ; 

     if(j < n)
        return input[count[j]] ;
     else
        return -1 ;

}

但是,我找不到找到第一次遇到的算法,除非有另一个 n 数组存储遇到整数的时间。

任何想法 ?第一个算法的任何其他实现?

谢谢

4

1 回答 1

4

你几乎拥有它:

#include <limits>
#include <iostream>

int firstNonRepeatingInteger(int* input, int n)
{
  int min = std::numeric_limits<int>::max() ;
  int max = std::numeric_limits<int>::min() ;

  // Find min/max values in input array.
  for(int i = 0; i < n; ++i)
  {
    if (input[i] > max)
      max = input[i];
    if (input[i] < min)
      min = input[i];
  }

  int* count;
  if (max - min + 1 > n)
  {
    count = new int[max - min + 1];
    // count has more elements than input, so only initialize
    // those elements which will be used.
    for(int i = 0; i < n; ++i)
      count[input[i] - min] = 0;
  }
  else
  {
    // Just initialize everything which is more efficient if
    // count has less elements than input.
    count = new int[max - min + 1]();
  }

  // Count number of occurrences.
  for(int i = 0; i < n; ++i)
    ++count[input[i] - min];

  // Find first non repeating element and return its index,
  // or -1 if there is none.
  int index = -1;
  for (int i = 0; i < n; ++i)
  {
    if (count[input[i] - min] == 1)
    {
      index = i;
      break;
    }
  }
  delete[] count;
  return index;
}

int main()
{
  int values[5] = {-2, 4, 6, 4, -2};
  int index = firstNonRepeatingInteger(values, 5);
  if (index >= 0)
  {
    std::cout << "Found first non repeating integer " << values[index] <<
      " at index " << index << "." << std::endl;
  }
  else
    std::cout << "Found no non repeating integer in array." << std::endl;
  return 0;
}

请注意,您的代码有几个问题:

  • 您从未删除分配的内存。
  • new int[max]不使用零初始化数组。你需要new int[max]()改用。注意空括号,它将所有元素设置为零(参见 ISO C++03 5.3.4[expr.new]/15)。
  • 输入数组中的负值将导致内存访问冲突。
于 2012-10-07T19:45:35.983 回答