第 01 天题目
0001. 两数之和
- 标签:数组、哈希表
- 难度:简单
题目大意
描述:给定一个整数数组 nums 和一个整数目标值 target。
要求:在该数组中找出和为 target 的两个整数,并输出这两个整数的下标。
解题思路
利用字典。字典中键值对信息为 target-nums[i] : i。i 为下标。
遍历数组,对于每一个数 nums[i],先查找字典中是否存在 target - nums[i],存在则输出 target - nums[i] 对应的下标和当前数组的下标 i。没有则在字典中存入 target-nums[i] 的下标 i。
代码
def twoSum(self, nums: List[int], target: int) -> List[int]:
numDict = dict()
for i in range(len(nums)):
if target-nums[i] in numDict:
return numDict[target-nums[i]], i
numDict[nums[i]] = i
return [0]
1929. 数组串联
- 标签:数组
- 难度:简单
题目大意
给你一个长度为 n 的整数数组 nums。
要求:构建一个长度为 2 * n 的答案数组 ans,数组下标从 0 开始计数 ,对于所有 0 <= i < n 的 i ,满足下述所有要求:
-
ans[i] == nums[i]。 -
ans[i + n] == nums[i]。
具体而言,ans 由两个 nums 数组串联形成。最后返回数组 ans 。
解题思路
使用 ans 作为答案数组。然后按顺序遍历两次数组 nums 中的元素,并依次添加到 ans 的尾部。最后返回 ans。
其实,Python 中更快速的做法是 return nums + nums。
代码
思路 1:
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
ans = []
for num in nums:
ans.append(num)
for num in nums:
ans.append(num)
return ans
思路 2:
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + nums
0771. 宝石与石头
- 标签:哈希表、字符串
- 难度:简单
题目大意
给定一个字符串 jewels 代表石头中宝石的类型,再给定一个字符串 stones 代表你拥有的石头。stones 中每个字符代表了一种你拥有的石头的类型。
要求:计算出拥有的石头中有多少是宝石。
注意:字母区分大小写,因此 a 和 A 是不同类型的石头。
解题思路
用 count 来维护石头中的宝石个数。先使用哈希表或者集合存储宝石。再遍历数组 stones,并统计每块石头是否在哈希表中或集合中,如果在,则 count += 1,如果不在哈希表或集合中,则不统计。
最后输出答案 count。
代码
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jewel_dict = dict()
for jewel in jewels:
jewel_dict[jewel] = 1
count = 0
for stone in stones:
if stone in jewel_dict:
count += 1
return count










