代码随想录算法训练营第七天

5.28面试题:输入字符串,输出去重后的结果(ACM模式)

def remove1(ss):
    return ''.join(sorted(set(ss)))

aa = input("请输入:")
print(remove1(aa))

##当长度较小时使用列表,列表查找的时间复杂度是o(n),而集合是o(1)
def remove3(ss):
    unique_chars = []
    for char in ss:
        if char not in unique_chars:
            unique_chars.append(char)
    return ''.join(unique_chars)

ss =input("请输入:")
print(remove3(ss))

##str.join() 是一个字符串方法,它用于连接一个序列(如列表或元组)中的字符串,而不是连接单个字符。并且,join() 方法是在调用它的字符串上执行的,而不是在结果字符串上。

##str() 函数用于将对象转换为字符串表示形式。


def remove2(ss):
    seen = {}
    result = ''
    for char in ss:
        if char not in seen:
##想添加单个字符用+=即可
            result += char
            seen[char] = True
    return result


aa = input("请输入:")
print(remove2(aa))

202. 快乐数

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。

class Solution:
    def isHappy(self, n: int) -> bool:
        result = []
        while n not in result:
            x = str(n)
            a = 0
            result.append(n)
            for i in x:
                a+=int(i)**2
            if a == 1:return True
            else: n = a
        return False

核心思路:如何求一个整数各个位上的平方和

将整数转化成字符串,再遍历整个字符串,转化为int求平方和

454. 四数相加 II

给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        hashmap = {}
        for i in nums1:
            for j in nums2:
                if i+j not in hashmap:
                    hashmap[i+j] = 1
                else : hashmap[i+j] += 1
        count = 0
        for i in nums3:
            for j in nums4:
                a = -i-j
                if a in hashmap:
                    count+=hashmap[a]
        return count
  1. 首先定义一个hashmap,key放s1,s2两数之和,value 放两数之和出现的次数。
  2. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
  3. 在遍历s3,s4数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value(出现次数)统计出来。
  4. 返回统计值 count 

383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        hashmap = {}
        for i in magazine:
            ##hashmap[i] = hashmap.get(i, 0) + 1
            if i not in hashmap:
                hashmap[i]=1
            else:hashmap[i]+=1
        for j in ransomNote:
            if j not in hashmap or hashmap[j]<=0:
                return False
            else:
                hashmap[j]-=1
        return True

    def canConstruct1(self, ransomNote: str, magazine: str) -> bool:
        ransom_count = [0] * 26
        magazine_count = [0] * 26
        for c in ransomNote:
            ransom_count[ord(c) - ord('a')] += 1
        for c in magazine:
            magazine_count[ord(c) - ord('a')] += 1
        return all(ransom_count[i] <= magazine_count[i] for i in range(26))

15. 三数之和

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,

使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

class Solution:
##暴力解法三层for循环
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums1 = sorted(nums)
        result = []
        for i in range(len(nums1)):
            for j in range(i+1,len(nums1)):
                for x in range(j+1,len(nums1)):
                    if nums1[i] + nums1[j]+nums1[x] == 0:
                        if [nums1[i],nums1[j],nums1[x]] not in result:
                            result.append([nums1[i],nums1[j],nums1[x]])
        return result 
class Solution:  
    def threeSum(self, nums: List[int]) -> List[List[int]]:  
        nums.sort()  
        result = []  
        for i in range(len(nums) - 2):  
            if nums[i] > 0:  
                break
            if i > 0 and nums[i] == nums[i - 1]:  
                continue              
            j = i + 1  
            x = len(nums) - 1               
            while j < x:  
                s = nums[i] + nums[j] + nums[x]  
                if s == 0:  
                    result.append([nums[i], nums[j], nums[x]])  
                    while j < x and nums[j] == nums[j + 1]:  
                        j += 1  
                    while j < x and nums[x] == nums[x - 1]:  
                        x -= 1  
                    j += 1  
                    x -= 1  
                elif s < 0:  
                    j += 1  
                else:  
                    x -= 1           
        return result

 18. 四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):

双指针法,减少一层循环(三数之和O(n2),四数之和O(n3))

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()  
        result = []  
        for a in range(len(nums)-3):
            if a > 0 and nums[a] == nums[a-1]: continue
            for b in range(a+1,len(nums)-2):
                if b > a+1 and nums[b] == nums[b-1]: continue                
                c = b+1
                d = len(nums)-1
                while c < d:
                    s = nums[a]+nums[b]+nums[c]+nums[d]
                    if s==target:
                        result.append([nums[a],nums[b],nums[c],nums[d]])
                        while c < d and nums[c] == nums[c+1]:
                            c+=1
                        while c < d and nums[d] == nums[d-1]:
                            d-=1
                        c+=1
                        d-=1
                    elif s>target:                     
                        d-=1
                    else:c+=1
        return result  

solution = Solution()
nums_str = input("请输入").split(",") 
nums = list(map(int, nums_str)) 
a = int(input())
solution = Solution()
result = solution.fourSum(nums,a)
print(result)                      

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值