美文网首页
【LeetCode】两数之和+宝石与石头

【LeetCode】两数之和+宝石与石头

作者: ShowMeCoding | 来源:发表于2021-11-15 21:32 被阅读0次

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

相关文章

网友评论

      本文标题:【LeetCode】两数之和+宝石与石头

      本文链接:https://www.haomeiwen.com/subject/fxtctrtx.html