DataWhale编程实践:Task03——查找1

具体算法思想参见
team-learning-program/LeetCodeClassification/3.查找.md
这部分主要是利用set,dict,map的一些属性和方法解决问题。

from typing import List


class Solution:
    # LeetCode 349 Intersection Of Two Arrays 1
    # 把nums1记录为set,判断nums2的元素是否在set中,是的话,就放在一个公共的set中,最后公共的set就是我们要的结果
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1 = set(nums1)
        return set([i for i in nums2 if i in nums1])

    # 通过set的内置方法来实现,直接求set的交集
    def intersection1(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        return set2 & set1

    # LeetCode 350 Intersection Of Two Arrays 2
    # 记录num1的字典,遍历nums2,比较nums1的字典的nums的key是否大于零,从而进行判断
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        from collections import Counter
        nums1_dict = Counter(nums1)
        res = []
        for num in nums2:
            if nums1_dict[num] > 0:
                # 说明找到了一个元素即在num1也在nums2
                res.append(num)
                nums1_dict[num] -= 1
        return res

    # LeetCode 242 Intersection Of Two Arrays 2
    # 选择dict的数据结构,将字符串s和t都用dict存储,而后直接比较两个dict是否相同
    def isAnagram(self, s: str, t: str) -> bool:
        from collections import Counter
        s = Counter(s)
        t = Counter(t)
        if s == t:
            return True
        else:
            return False

    # LeetCode 202 Happy number
    # 用set的数据结构。每次对求和的数进行append,当新一次求和的值存在于set中时,就return false
    # # 一般对多位数计算的套路是:
    # # 循环从后向前取位数
    # while n > 0:
    # # 取最后一位:
    # tmp = n % 10
    # # 再截掉最后一位:
    # n = n // 10
    def isHappy(self, n: int) -> bool:
        already = set()
        while n != 1:
            sum = 0
            while n > 0:
                # 取n的最后一位数
                tmp = n % 10
                sum += tmp ** 2
                # 将n的最后一位截掉
                n //= 10
            # 如果求的和在过程中出现过
            if sum in already:
                return False
            else:
                already.add(sum)
            n = sum
        return True

    # LeetCode 290 Word Pattern
    # 将原来的dict通过map映射为相同的key,再比较相同key的dict是否相同
    def wordPattern(self, pattern, str):
        str = str.split()
        return list(map(pattern.index, pattern)) == list(map(str.index, str))

    # LeetCode 205 Isomorphic Strings
    # 建两个dict,比较怎样不同
    def isIsomorphic(self, s: str, t: str) -> bool:
        return list(map(s.index, s)) == list(map(t.index, t))

    # LeetCode 451 Sort Characters By Frequency
    # 使用字典统计频率,对字典的value进行排序,最终根据key的字符串乘上value次数,组合在一起输出。
    def frequencySort(self, s: str) -> str:
        from collections import Counter
        s_dict = Counter(s)
        # sorted返回的是列表元组
        s = sorted(s_dict.items(), key=lambda item: item[1], reverse=True)
        # 因为返回的是字符串
        res = ''
        for key, value in s:
            res += key * value
        return res


if __name__ == "__main__":
    solution = Solution()

    # LeetCode 349 Intersection Of Two Arrays 1
    nums1 = [1, 2, 2, 1]
    nums2 = [2, 2]
    print(solution.intersection(nums1, nums2))
    print(solution.intersection1(nums1, nums2))

    # LeetCode 350 Intersection Of Two Arrays 2
    num1 = [1, 2, 2, 1]
    num2 = [2, 2]
    print(solution.intersect(num1, num2))

    # LeetCode 242 Intersection Of Two Arrays 2
    s = "anagram"
    t = "nagaram"
    print(solution.isAnagram(s, t))
    s = "rat"
    t = "car"
    print(solution.isAnagram(s, t))

    # LeetCode 202 Happy number
    num = 19
    print(solution.isHappy(num))

    # LeetCode 290 Word Pattern
    pattern = "abba"
    str1 = "dog cat cat dog"
    print(solution.wordPattern(pattern, str1))
    pattern = "abba"
    str1 = "dog cat cat fish"
    print(solution.wordPattern(pattern, str1))
    pattern = "aaaa"
    str1 = "dog cat cat dog"
    print(solution.wordPattern(pattern, str1))
    pattern = "abba"
    str1 = "dog dog dog dog"
    print(solution.wordPattern(pattern, str1))

    # LeetCode 205 Isomorphic Strings
    s = "egg"
    t = "add"
    print(solution.isIsomorphic(s, t))
    s = "foo"
    t = "bar"
    print(solution.isIsomorphic(s, t))
    s = "paper"
    t = "title"
    print(solution.isIsomorphic(s, t))

    # LeetCode 451 Sort Characters By Frequency
    s = "tree"
    print(solution.frequencySort(s))
    s = "cccaaa"
    print(solution.frequencySort(s))
    s = "Aabb"
    print(solution.frequencySort(s))

这部分主要是利用二分查找的思想解决问题。
最后一个split array largest sum的解题思路有两种,一种是动态规划的思想,一种是二分查找,可以参考阅读[LeetCode] 410. Split Array Largest Sum 分割数组的最大值LeetCode410. Split Array Largest Sum(分割数组的最大值)进一步加深理解。当然,关于leetcode网上有大量资料解释解题思路,可以直接搜索查阅。

from typing import List


class Solution:

    # LeetCode 35. Search Insert Position
    def searchInsert(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid
        return lo

    # LeetCode540. Single Element in a Sorted Array
    def singleNonDuplicate(self, nums):
        lo, hi = 0, len(nums) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] == nums[mid ^ 1]:
                lo = mid + 1
            else:
                hi = mid
        return nums[lo]

    # LeetCode 410. Split Array Largest Sum
    def splitArray(self, nums: List[int], m: int) -> int:

        def helper(mid):
            res = tmp = 0
            for num in nums:
                if tmp + num <= mid:
                    tmp += num
                else:
                    res += 1
                    tmp = num
            return res + 1

        lo, hi = max(nums), sum(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if helper(mid) > m:
                lo = mid + 1
            else:
                hi = mid
        return lo


if __name__ == "__main__":
    solution = Solution()

    # LeetCode 451 Sort Characters By Frequency
    s = "tree"
    print(solution.frequencySort(s))
    s = "cccaaa"
    print(solution.frequencySort(s))
    s = "Aabb"
    print(solution.frequencySort(s))

    # LeetCode 35. Search Insert Position
    sources = [1, 3, 5, 6]
    target = 5
    print(solution.searchInsert(sources, target))
    sources = [1, 3, 5, 6]
    target = 2
    print(solution.searchInsert(sources, target))
    sources = [1, 3, 5, 6]
    target = 7
    print(solution.searchInsert(sources, target))
    sources = [1, 3, 5, 6]
    target = 0
    print(solution.searchInsert(sources, target))

    # LeetCode540. Single Element in a Sorted Array
    sources = [1, 1, 2, 3, 3, 4, 4, 8, 8]
    print(solution.singleNonDuplicate(sources))
    sources = [3, 3, 7, 7, 10, 11, 11]
    print(solution.singleNonDuplicate(sources))

    # LeetCode 410. Split Array Largest Sum
    nums = [7, 2, 5, 10, 8]
    m = 2
    print(solution.splitArray(nums, m))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值