前言
今天的内容主要是学习哈希表的使用,题目是
1.给两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
2.给一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
一、第一题
1.Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
a = set()
if(headA == None or headB == None):
return None
pp = headA
while(pp):
a.add(pp)
pp = pp.next
qq = headB
while(qq):
if qq in a:
return qq
else:
qq = qq.next
return None
python中可以使用集合set和字典dict来实现哈希表的功能,这里因为不需要考虑下标,所以使用set,遍历headA,将遍历过的数据存在set中,之后遍历headB,如果结点出现在哈希表set中,就会返回这个结点,否则就会添加进set中
2.C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
unordered_set<ListNode*> hashmap;
if((headA==NULL && headB ==NULL)||(headA==NULL || headB ==NULL))
{
return NULL;
}
ListNode * pp =headA;
while(pp)
{
hashmap.insert(pp);
pp = pp->next;
}
ListNode*qq = headB;
while(qq)
{
unordered_set<ListNode*>::iterator it = hashmap.find(qq);
if(it != hashmap.end())
{
return *it;
}
qq = qq->next;
}
return NULL;
}
};
主要思想与上述类似,只不过在c++中是使用unordered_set和unordered_map这两个容器实现哈希表,unordered_set中存放的元素是ListNode*指针,如果遍历的元素在哈希表中,就会返回结点指针。
二、第二题
1.Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
hashset = set()
if(head ==None):
return False
pp = head
while(pp and pp.next):
if pp in hashset:
return True
else:
hashset.add(pp)
pp = pp.next
return False
原理与上道题目类似,记录下没有出现过的元素,并与新遍历的元素比较
2.C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> hashmap;
ListNode* pp =head;
if(head==NULL)
{
return false;
}
while(pp && pp->next)
{
unordered_set<ListNode*>::iterator it = hashmap.find(pp);
if(it != hashmap.end())
{
return true;
}
else
{
hashmap.insert(pp);
pp = pp->next;
}
}
return false;
}
};
这里的原理与上面一样,但是这里有一个点需要说明,链表结点pp,如果在循环中需要使用pp->next,需要确保pp->next不为空,否则会报错
总结
哈希表大多是使用在一些需要比较的情况下,本质就是集合或者是字典,只不过里面存放的元素是各种各样的。
比如下面一道题是用到了字典
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashdict = dict()
len1 = len(nums)
for i in range(len1):
s = target - nums[i]
if s in hashdict:
return [hashdict[s], i]
else:
hashdict[nums[i]] = i
return False
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int num = nums.size();
unordered_map<int, int> hashmap;
for(int i = 0; i< num; i++)
{
int s = target - nums[i];
unordered_map<int, int>::iterator it = hashmap.find(s);
if(it != hashmap.end())
{
return{it->second, i};
}
else
{
hashmap.insert(make_pair(nums[i], i));
}
}
return{};
}
};
这里将存入的元素作为key,下标作为value,这样可以直接查找元素是否在字典的key中出现过,如果出现过,就返回下标value