This repository has been archived on 2023-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
NumberOnlyOnce/main.cpp
2023-06-15 22:49:30 +08:00

47 lines
1.4 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
// 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
int singleNumber(int nums[], int numsSize) {
int tempSingle = 0;
for (int i = 0; i < numsSize; ++i) {
for (int j = 0; j < numsSize; ++j) {
if (i == j) continue;
if (nums[i] == nums[j]) {
nums[i] = nums[j] = 0;
}
}
}
for (int i = 0; i < numsSize; ++i) {
if (nums[i] != 0) {
if (tempSingle == 0) tempSingle = nums[i];
else return -1;
};
}
return tempSingle;
}
int main() {
while (true) {
int numsSize;
printf("[INFO] 请输入数组大小: ");
scanf("%d", &numsSize);
if (numsSize == -1) break;
if (numsSize == 0) {
printf("[WARNING] 无法完成计算最少需要1位数\n\n");
continue;
}
getchar();
printf("[INFO] 请输入数组内容(中间使用逗号隔开): ");
int nums[numsSize];
for (int i = 0; i < numsSize - 1; ++i) {
scanf("%d,", &nums[i]);
}
scanf("%d", &nums[numsSize - 1]);
getchar();
// upload data to singleNumber function
printf("[OUTPUT] 输出结果: %d\n", singleNumber(nums, numsSize));
printf("\n");
}
printf("[SYSTEM] 已退出\n");
return 0;
}