题解 | #序列中整数去重#
序列中整数去重
https://www.nowcoder.com/practice/6564a2f6e70f4153ad1ffd58b2b28490
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> int* derepeat(int* arr, int n, int* returnSize) { int* ret = (int* )calloc(sizeof(int) * n, sizeof(int)); if (ret == NULL) { // 内存分配失败处理 fprintf(stderr, "Memory allocation failed.\n"); exit(EXIT_FAILURE); } int k = 0; for (int i = 0; i < n; ++i) { _Bool flag = true; for (int j = 0; j < n; ++j) { if (ret[j] == arr[i]) { flag = false; break; } } if (flag) { ret[k++] = arr[i]; } } *returnSize = k;//更新返回数组长度 return ret; } int main() { int n, len; scanf("%d", &n); int* arr = (int* )malloc(sizeof(int) * n); if (arr == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(EXIT_FAILURE); } for (int i = 0; i < n; ++i) { scanf("%d", &arr[i]); } int* ans = derepeat(arr, n, &len); for (int i = 0; i < len; ++i) { printf("%d ", ans[i]); } free(arr); free(ans); return 0; }