《LeetCode 热题 100》

《LeetCode 热题 100》持续更新

一、hash表

1.两数之和

【题解】遍历nums数组,判断target-num是否在hash表中,如果不在就把当前遍历的数字和其下表加入到hash表中,如果在则返回hash表中数字的下标以及当前数字下标。

当然也可以使用暴力求解,第二层遍历看target-num是否在数组nums中。

【代码】

python 复制代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap=dict()
        for i,num in enumerate(nums):
            if target-num in hashmap:
                return [hashmap[target-num],i]
            hashmap[nums[i]]=i

49.字母异位词分组

【题解】对字符串数组中每个单词进行排序,使得其按正序排序。接着遍历排序过的字符串数组,并把排列相同的单词放入到hash表中,key为字母排序,值为字符串数组中的单词。

【代码】

python 复制代码
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
res = dict()
sortedStrs = [''.join(sorted(list(s))) for s in strs]
for i in range(len(sortedStrs)):
    if sortedStrs[i] not in res.keys():
        res[sortedStrs[i]] = [strs[i]]
    else:
        res[sortedStrs[i]].append(strs[i])
print( list(res.values()))

128.最长连续序列

【题解】用一个set存储list,然后遍历这个set,看当前数的前一个数在不在set中,如果在就下一个,如果不在一直循环直到下一个数不在。为什么要查看当前数的前一个数在不在,是因为避免重复循环,就是要找到第一个循环的数(即最小的数)。

python 复制代码
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        max_len=0
        num_set =set(nums)
        for num in num_set:
            if (num-1) not in num_set:
                seq_len=1
                while (num+1) in num_set:
                    seq_len+=1
                    num+=1
                max_len = max(max_len,seq_len)
        
        return max_len
相关推荐
山登绝顶我为峰 3(^v^)31 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.2 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森4 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack6 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客6 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠6 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988947 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼7 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield8 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦8 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt