160.相交链表
题目
![](https://img-blog.csdnimg.cn/img_convert/cb5ee83050566b2f9b5d1c10a2a0e520.png)
![](https://img-blog.csdnimg.cn/img_convert/ed332f7863eac6b3491ef731f0126804.png)
题解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//哈希结构
typedef struct HashNode{
struct ListNode * ptr;
UT_hash_handle hh;
}HashNode,*HashTable;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
//哈希表
HashTable ht = NULL;
struct ListNode * tempL = headA;
while(tempL != NULL){
//添加进哈希表
HashNode* tempH = (HashNode*)malloc(sizeof(HashNode));
tempH->ptr = tempL;
HASH_ADD_PTR(ht,ptr,tempH);
tempL = tempL->next;
}
tempL = headB;
while(tempL != NULL){
//查找哈希表
HashNode* result;
HASH_FIND_PTR(ht,&tempL,result);
if(result != NULL){
return result->ptr;
}
tempL = tempL->next;
}
return NULL;
}
要点
这种查找链表中元素的题都可以想想哈希表,先把A链表存进哈希表中,再用B链表去查找哈希表。
哈希表使用规则:
①引入哈希表头文件:
#include <uthash.h>
②创建哈希表的结构:
typedef struct HashNode{
//里面的东西都是可以自己设置的,这里随便设置一个int类型的abc。
int abc;
//哈希表句柄,不可少
UT_hash_handle hh;
}HashNode,*HashTable;
③初始化哈希表,后续添加节点都是添加到这里面。
HashTable ht = NULL;
④添加元素,每次都是要新建一个哈希结点然后填充各种属性,这样整个结构就形成了一个“值”,然后从这个结构中选择一个属性当做“键”。
HashNode * hd = (HashNode*)malloc(sizeof(HashNode));
//填充各种属性
hd->abd = 123;
//插入到哈希表中
HASH_ADD_INT(ht,abc,hd);
这里说明一下HASH_ADD_INT的使用说明,第一个参数是要插入的哈希表(指针形式);第三个参数是哈希结点(指针形式);第二个参数是这个结点中的要拿出来作为键的属性名。
⑤查找元素
HashNode* result;
HASH_FIND_INT(ht,&tempL,result);
这里说明一下HASH_FIND_INT的使用说明,第一个参数是要查找的哈希表(指针形式);第二个参数是键的地址,反正就是之前添加时的键名加个&;第三个参数是通过键名查找到的哈希结点,也就是值,要先申请一个空间接收。
217.存在重复元素
题目
![](https://img-blog.csdnimg.cn/img_convert/475cc9b15d8f16c63a57df5936190a04.png)
题解
int cmp (const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
bool containsDuplicate(int* nums, int numsSize){
qsort(nums,numsSize,sizeof(nums[0]),cmp);
for( int i = 0; i < numsSize-1; i++) {
if( nums[i] == nums[i+1] ){
return true;
}
}
return false;
}
要点
c语言有自带快排函数。但是需要自己设置一个比较函数。
比较函数的形参可以是任意的结构,如果是结构那么函数内比较时比较的是这两个结构中的某一属性。