牛客网/X为机试/HJ8
描述
数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
输入描述:
先输入键值对的个数
然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
分析
这题的重点在于查找时间和存储空间的处理即数据结构的选取。
到底是map还是数组还是哈希表可以根据key的范围以及key-value对的个数选取。
1:如果key取值范围小,那么数组是最合适的。但本题不适合,因为并没有给出key的范围,如果key很大如Integer.MAX-1,那么直接开一个这么大的数组会崩的的
2:如果key的取值范围很大,但是key的个数少,那么哈希表比较合适
3:如果key的取值范围很大而且key的个数很多,那么tree是比较合适的。
学习代码:
定长数组
代码量少,简单
#include <stdio.h>
int main()
{
int array[1001]={0};
int num=0;
int index=0,value=0;
scanf("%d",&num);
while(num--)
{
scanf("%d %d",&index,&value);
array[index]+=value;
}
for(index=0;index != 1000;index++)
{
if(array[index] != 0)
{
printf("%d %d\n",index,array[index]);
}
}
}
哈希表
采用除留余数法构造,开放定址法处理冲突的哈希表。
能处理key值分布分散的数据,比起定长数组更省空间,适用性更广。
但是不具有排序能力,比起红黑树来说,要多一步排序除重再输出的步骤。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#define NULLKEY -32768
#define SUCCESS 1
#define UNSUCCESS 0
typedef struct
{
int key;
int value;
} HashNode;
typedef struct
{
HashNode *elem;
int count;
} HashTable;
int InitHashTable(HashTable *t, int cnt)
{
t->count = cnt;
t->elem = (HashNode *)malloc(cnt * sizeof(HashNode));
for (int i = 0; i < cnt; i++)
{
t->elem[i].key = NULLKEY;
}
return SUCCESS;
}
/* 散列函数 */
int Hash(HashTable *t, int key)
{
return key % t->count; /*除留余数法*/
}
int SearchHash(HashTable *t, int key, int *index)
{
*index = Hash(t, key);
while (t->elem[*index].key != key)
{
if (t->elem[*index].key == NULLKEY || t->elem[*index].key == Hash(t, key))
return UNSUCCESS;
*index=(*index+1) % t->count;
}
return SUCCESS;
}
void InsertHash(HashTable *t, HashNode *node)
{
int index = Hash(t, node->key);
if(SearchHash(t,node->key,&index))
{
t->elem[index].value += node->value;
}
else
{
t->elem[index] = *node;
}
}
void DestroyHash(HashTable *t)
{
free(t->elem);
}
void Sort(int arr[],int len)
{
int i,j,val;
for(i=1;i<len;i++)
{
val=arr[i];
for(j=i-1;j>=0 && arr[j]>val;j--)
{
arr[j+1]=arr[j];
}
arr[j+1]=val;
}
}
int main()
{
int cnt;
HashNode node;
HashTable t;
scanf("%d",&cnt);
InitHashTable(&t,cnt);
int *keyarr=(int *)malloc(cnt * sizeof(int));
for(int i=0;i<cnt;i++)
{
scanf("%d %d",&node.key,&node.value);
keyarr[i]=node.key;
InsertHash(&t,&node);
}
Sort(keyarr,cnt);
for(int i=0;i<cnt;i++)
{
if(keyarr[i] == keyarr[i+1] )
continue;
int index=0;
SearchHash(&t,keyarr[i],&index);
printf("%d %d\n",t.elem[index].key,t.elem[index].value);
}
DestroyHash(&t);
free(keyarr);
return 0;
}