哈希思想 (leetcode1两数之和and202快乐数 ) python

leetcode1 两数之和

  1. 题目:
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    示例:
    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

  2. 思路:
    思路1.两层for循环遍历列表,但时间复杂度是O(N²)。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j] 

思路2.哈希表(hash table) :把key值映射到哈希表中一个位置来访问,时间复杂度是O(N)。哈希表知识,参考Hash表的理论基础与具体实现(详细教程)

  • 初始化nums_hash
  • 寻找出if存在和为target的2个数
  • 返回2个数下标
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_hash = {} 
        nums_len = len(nums)
        for i in range(nums_len):
            dif = target - nums[i]
            if dif in nums_hash: 
                return [nums_hash[dif], i]
            nums_hash[nums[i]] = i
        return []
    
if __name__ == '__main__':
    nums = [1, 2, 3]
    target = 3
    print(Solution().twoSum(nums, target))    

leetcode202 Happy Number

  1. 题目:
    编写一个算法来判断一个数是不是“快乐数”。
    一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
    示例:
输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
  • 思路:
  • map返回list求和。sums = sum(map(lambda x:x**2,map(int,str(n)))) # lambda是一个匿名函数,外层map(a,b,b2,…)是一个模型,a是一个函数,b,b2…是可迭代对象,map本身就是可迭代对象。内层map(int,str(n))的意思是,将一个数转为字符串后,就变成了一个map迭代对象。即理解为,假设输入为19,此时为一个list=[1,9]。外层的map(labda函数…,map()),做的工作就是list=[1平方,9平方],然后在sum(list)最后1平方+9平方得到82。
  • 之后寻找快乐数,sums == 1 即True。另外无限循环,每次sums都存在hash字典里,所以只要后面有sums重复在字典里,即False。然后不断迭代。(hash即dict使用)
class Solution:
    def __init__(self):
        self.hash_dict = {}
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        sums = sum(map(lambda x:x**2,map(int,str(n))))	#实现一个数round拆分平方求和
        if sums == 1:
            return True
        if sums in self.hash_dict:
            return False
        else:
            self.hash_dict[sums] = 0
        return self.isHappy(sums)

参考快乐数

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值