class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numsMap = {}
for idx,num in enumerate(nums):
resIdx = numsMap.get(target - num)
if resIdx is not None:
return [resIdx,idx]
numsMap[num] = idx
https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
wordsMap = {}
for word in strs:
sortedWord = "".join(sorted(word))
wordsList = wordsMap.get(sortedWord)
if wordsList:
wordsList.append(word)
else:
wordsMap[sortedWord] = [word,]
return list(wordsMap.values())
128. 最长连续序列
- 创建一个空的哈希表
num_set
,用于存储数组中的唯一数字。 - 初始化最长序列长度
max_length
为 0。 - 遍历数组
nums
中的每个数字:- 如果当前数字不在
num_set
中,则将其加入num_set
。 - 然后,检查当前数字的前一个数字
num-1
是否在num_set
中,以及当前数字的后一个数字num+1
是否在num_set
中。如果存在,就找到了一个新的连续序列,更新当前序列的长度,并更新max_length
。
- 如果当前数字不在
- 返回
max_length
作为结果。
下面是这个算法的 Python 实现:
def longest_consecutive(nums):
num_set = set(nums)
max_length = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_length = 1
while current_num + 1 in num_set:
current_num += 1
current_length += 1
max_length = max(max_length, current_length)
return max_length
https://leetcode.cn/problems/move-zeroes/description/?envType=study-plan-v2&envId=top-100-liked1) 使用冒泡排序,但是效率太低
class Solution {
public void moveZeroes(int[] nums) {
for(int j = nums.length-1; j > 0; j--){
for(int i=0; i<j; i++){
if(nums[i] == 0 && nums[i+1] != 0){
nums[i] = nums[i+1];
nums[i+1] = 0;
}
}
}
}
}
2) 可以在遍历时统计出现了几个0
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
zeroesCnt = 0
for idx,n in enumerate(nums):
if n == 0:
zeroesCnt += 1
else:
nums[idx-zeroesCnt] = n
if zeroesCnt:
for i in range(zeroesCnt):
nums[len(nums)-i-1] = 0