找出重复的号码

时间:2010-12-23 09:09:10

标签: c

在数组[10]中,数组中有1到9的数字,其中一个数字重复(重复数也在1到9之间)如何在不使用循环的情况下找到重复的数字和数组从上到下只能横过一次。

这不是作业,这是在采访中提出的

6 个答案:

答案 0 :(得分:8)

最短的答案必须基于弗拉基米尔的回答。没有for循环,但它也不能扩展到可变大小的数组。它是:

int repeated_number = array[9]+array[8]+array[7]+array[6]+array[5]
                     +array[4]+array[3]+array[2]+array[1]+array[0]-45;

甜蜜而简单,回答这个问题。我认为,问题在于所有回答这个问题的人都习惯于编写可以处理变量情况的合理代码,但这是一个简单的简单问题,所以应该简单回答。

答案 1 :(得分:7)

int sum = 0;
for (int i = 9; i >= 0; --i)
    sum+=array[i];
int repeatedNumber = sum - 45; // 45 = 1+...+9

这个解决方案确实使用循环,但你的条件是有争议的 - 遍历数组意味着使用了循环

答案 2 :(得分:3)

制作一组10个布尔。每个bool代表其各自的数字已经发生。如果在写入true时发现bool,则重复该数字。

答案 3 :(得分:0)

我给出的解决方案来自CommanderZ,但唯一的区别是我感到无聊,我不想去学习,所以我做了代码。

int FindDuplicate(int index)
{
    static bool initialized = false;
    static bool Existance[10];
    if(!initialized)
    {
        for (int i = 0 ; i < 10 ; i++)
            Existance[i] = false;
        initialized = true;
    }

    if(index == -1)
        return 0;

    if(Array[index] == true)
        return index;
    else
        Array[index] = true;

    return FindDuplicate(index - 1); //edit-fix

}

另请参阅此线程可能有点类似:Given an array with multiple repeated entries, fnd one repeated entry O(N) time and constant space

还有这个:Array Homework Question

答案 4 :(得分:0)

我也很无聊。这是使用递归和Vladimirs减法技巧的解决方案:

int find_dupe(int* array, int len)
{
    static int sum = 0;
    sum += array[0];

    if(len == 1)
        return sum - 45;

    return find_dupe(array+1, len-1);
}

int main()
{
    int array[10] = { 9, 2, 5, 8, 6, 7, 1, 3, 4, 2 };

    printf("dupe: %i\n", find_dupe(array, 10));

    return 0;
}

答案 5 :(得分:0)

尝试使用布尔数组来指示值是否存在。使用true表示该号码存在。

int main(void)
{
  const unsigned int array_values[10] = {1, 2, 3, 3, 4, 5, 6, 7, 8, 9};
  bool               is_resident[10] = {false};
  bool               duplicate = false;
  unsigned int       index = 0;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  duplicate = duplicate || is_resident[array[index]];
  is_resident[array[index++]] = true;
  std::cout << "Duplicate found: " << (char *)(duplicate ? "true" : "false") << std::endl;
  return 0;
}

上述代码未针对此问题进行测试和专业化。这段代码在生活中没有其他目的,不是一般化的。

注意:在此示例中没有使用或损坏循环。
“总有第三种选择。” - Thomas Matthews