您的位置:首页 > 产品设计 > UI/UE

PAT-A 1041. Be Unique (20)

2017-03-07 17:51 399 查看
题目链接在此

思路

用一个二维hashTable第一位保存对应数字的输入次数,第二维保存第一次输入该数字的次序(在第几个输入),最后输出次数等于一并且最先输入的那个数。

PS:也可以把hashTable定义成一维,用另一个数组保存输入,那么输入的数在这个数组中位置也就代表了输入的顺序。

AC代码

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

int hashTable[10010][2]={0}; //第二维记录第一次输入的次序

int main(){

int N;
scanf("%d",&N);

int temp;
for(int i = 0; i < N; i++){
scanf("%d",&temp);
hashTable[temp][0]++;
if(hashTable[temp][1] == 0){ //第一次输入这个数
hashTable[temp][1] = i+1;
}
}

int order = 100001, res = -1; //order记录输入的次序,res记录第一次输入的唯一的数 ,注意Order的初值
for(int i = 1; i < 10001; i++){
if(hashTable[i][0] == 1 && hashTable[i][1] < order){ //输入次序是最先的,并且是唯一的
order = hashTable[i][1];
res = i;
}
}

if(res == -1) //有唯一的值
printf("None\n");
else //没有唯一的值
printf("%d\n", res);

return 0;
}


PS提到的思想的代码:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

int hashTable[10010] = {0}; //第二维记录第一次输入的次序
int a[100010];  //注意数组大小

int main(){

int N;
scanf("%d",&N);

for(int i = 0; i < N; i++){
scanf("%d",&a[i]);
hashTable[a[i]]++;
}

int res = -1;
for(int i = 0; i < N; i++){
if(hashTable[a[i]] == 1){
res = a[i];
break;
}
}

if(res == -1) //没有唯一的值
printf("None\n");
else //有唯一的值
printf("%d\n", res);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: