1-两数之和
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class Solution:
def twoSum(self, nums:List[int], target:int) -> List[int]:
hashtable = dict()
for i in range(len(nums)):
if target - nums[i] in hashtable:
return [i, hashtable[target-nums[i]]]
hashtable[nums[i]] = i
return []
771- 宝石与石头
输入:jewels = "aA", stones = "aAAbbbb"
输出:3(在石头中找出宝石的个数)
- 方法1:hashmap方法
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
hashMap = {}
for i in range(len(stones)):
if stones[i] in hashMap:
hashMap[stones[i]] += 1
else:
hashMap[stones[i]] = 1
# print(hashMap)
res = 0
for j in jewels:
if j in hashMap:
res += hashMap[j]
return res
- 方法2:直接检索并计数
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
res = 0
for s in stones:
if s in jewels:
res += 1
return res
网友评论