在数组中找到孤独的整数

Find the lonely integer in an array

如果可以,请参考 this hackerrank 挑战。

问题是在一个数组中找到孤独的整数,给定一个数组只包含一对,除了一个孤独的整数。

这个测试用例有问题

9
4 9 95 93 57 4 57 93 9

9 是数组大小,下面是数组

查看 //------ 突出显示的代码部分

如果我将 scanf("%d", &n) 放在 int arr[n] 之上,代码可以正常工作,但反过来会产生可怕的结果。

#include <stdio.h>

int lonely_integer(int* a, int size);

int main(){
    //n is size of array, i is counter variable
    int n, i, result;
    // ---------------------
    int arr[n];
    scanf("%d", &n);
    // ---------------------
    printf("%d\n", n);
    for(i = 0; i < n; i++){
        scanf("%d", &arr[i]);
    }
    result = lonely_integer(arr, n);
    printf("%d", result);
    return 0;
}


int lonely_integer(int* a, int size){
    int i;
    int res = 0;
    for(i = 0; i < size; i++){
        res = res ^ a[i];
    }

    return res;
}

您想使用:

#include <stdlib.h>
/* ... */
int *arr;
scanf("%d", &n);
arr = malloc(sizeof(int) * n);

这样,arr 会在运行时动态分配,因此它可以是任意大小,具体取决于输入 n

你最初做的事情(即在通过 scanf 收到 n 后声明 arr[n]scanf("%d", &n); int arr[n];)不是一个好主意,因为它使用了 Variable -Length Arrays,C 的一个特性,在最新的 C 标准中不是强制性的。

你看,arr是在编译时创建的,你通常只能用编译时已知的常量表达式初始化它,n,作为用户输入收到的变量,显然不是。可变长度数组是该语言的一项功能,它基本上允许您绕过此规则,即它们使您能够将数组初始化为编译时未知的长度。这已在 C99 中标准化,但在 C11.

中被列为 "optional"

你在那之后所做的事情 (int arr[n]; scanf("%d", &n);) 是非常不合逻辑的,因为,好吧,你将 arr 声明为 n 个整数的数组 before 您收到 n 的值作为用户输入,并且知道它的值。它打印垃圾,因为 n 最初被初始化为一个未指定的 "garbage" 值,这就是你声明它时 VLA 的大小:

int arr[n]; //n is garbage at this point, you have no idea how large arr will be!
scanf("%d", &n); //you got the value of n that you needed, but too late, alas!

问题中给出的范围n1 <= N < 100,这个范围很小,可以使用variable length array。但是你在这里做错了

int arr[n];   // n is uninitialized. Its value is indeterminate.
scanf("%d", &n);  

您需要先初始化 n,然后再将其用作数组大小

scanf("%d", &n);
int arr[n];

使用未初始化的变量分配数组,将导致未定义的行为,编译器将抛出警告 "variable used uninitialized in this function"

如果您在运行时获取数组的大小,明智的做法是使用动态内存分配,正如@Mints97 发布的那样

int data_size;
int *data_array;
scanf("%d", &data_size);
data_array = (int*)calloc(data_size,sizeof(int));
/*
 .
*/
// Free the memory at the end
free(data_array);
data_array = NULL;

如果想在编译时设置数组的大小,可以定义一个宏

#define DATA_SIZE 9

或者在编译代码的时候设置宏

gcc test.c -o test -DDATA_SIZE=9 -Wall

'n' 的值必须在 used.like 您正在使用

之前定义

int arr[n];

在读取 'n' 的值之前。所以编译器不知道,数组中有多少元素 'n' 可能是垃圾 value.how 它应该分配给数组的内存量。

因此在使用它作为数组定义之前,您必须阅读 'n' 的值。

function lonelyInteger(a){
 let n = [1,2,3,4,3,2,1];
 let unique = a.filter(function(value){
 return a.indexOf(value) === a.lastindexOf(value)
 })
 retun unique[0]
 }