返回信息流题库里面的一道single number,代码敲得快但是一直出现运行时错误。。。数组感觉并没有越界,请教各位大佬。靴靴[ema23]
题目描述
Given an array with N integers where all elements appear three times except for one. Find out the one which appears only once.
输入格式
Several test cases are given, terminated by EOF.
Each test case consists of two lines. The first line gives the length of array N(1≤N≤105), and the other line describes the N elements. All elements are ranged in [0,263-1].
输出格式
Output the answer for each test case, one per line.
我的代码,比较笨。。。
#include<iostream>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
int num;
int count[2048] = { 0 };
int i;
for (int i = 0; i <= n-1; i++)
{
cin >> num;
int k = num;
count[k]++;
}
for (i = 0 ; i <= n-1; i++)
{
if (count[i] == 1)
cout << i << endl;
}
}
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #92727同步于 2017/4/2
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖
【问题】求救大佬
czl19980530
2017/4/2镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
我看到网上好多都是用异或的位运算做得。。。道理我懂,但是我就是不懂我的代码问题在哪里
【 在 fjjnyf 的大作中提到: 】
: 其实元素范围是2^63-1,网页上显示错了
: 其他的我就不大懂了,建议去网上搜一下,有源码
帮你呼叫大神
【 在 czl19980530 (等待的荒芜亦或是什么) 的大作中提到: 】
: 题库里面的一道single number,代码敲得快但是一直出现运行时错误。。。数组感觉并没有越界,请教各位大佬。靴靴[ema23]
: 题目描述
: Given an array with N integers where all elements appear three times except for one. Find out the one which appears only once.
: ...................
大概有3个问题吧
1、count越界的问题,实际上如果数据到2^63,你这个思路就必须开那么大的数组,应该会给你一个runtime error,推荐你使用unordered_map,但是鉴于oj不支持C++11,可以用退求其次用map
2、如果是2^63-1,那么你应该使用long long int去定义num,同理k也是(虽然不知道为什么要定义k)
3、int count[2048] = { 0 };这种赋值方式并不能保证数组全被赋为0,只能保证count[0]是0,请使用memset或者循环