LeetCode-排序-Easy

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




242. Valid Anagram 有效的字母异位词

解题思路:异位词 即单词中的字母需要一样
可以统计每种字母个数 如果是异位词需要满足 每种单词个数一致

def isAnagram(s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    if len(s)!=len(t):
        return False
    
    for x in set(s):
        if s.count(x) != t.count(x):
            return False
    return True

349. Intersection of Two Arrays 两个数组的交集

解题思路:取交集 且无重复 使用set

def intersection(nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: List[int]
    """
    n1 = set(nums1)
    n2 = set(nums2)
    return list(n1&n2)

350. Intersection of Two Arrays II 两个数组的交集 II

解题思路:ans1: 接349 获取不重复的交集l 遍历l中的元素 找到两个集合中该元素出现最少的次数 添加进答案
ans2: 将第一个集合编成 字符-次数 的字典 遍历第二个集合 如果某一个字符在字典中并且次数不为0 则加入 字典中的次数减一

from collections import defaultdict

def intersect(nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: List[int]
    """
    n1=set(nums1)
    n2=set(nums2)
    l = list(n1&n2)
    res=[]
    for x in l:
        num = min(nums1.count(x),nums2.count(x))
        res.extend([x]*num)
    return res

def intersect2(nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: List[int]
    """
    d = defaultdict(int)
    res=[]
    for i in nums1:
        d[i]+=1
    for i in nums2:
        if d[i]>0:
            res.append(i)
            d[i]-=1
    return res

922. Sort Array By Parity II 按奇偶排序数组 II

解题思路:1. 分奇数偶数两个list 在偶数list中的奇数位 插入奇数
2. 用ij记录偶数奇数位置 遍历list 如果是偶数放入i位置 奇数放入j位置

def sortArrayByParityII(A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    odd = [x for x in A if x%2==1]
    ans = [x for x in A if x%2==0]
    
    p = 1
    for i in odd:
        ans.insert(p,i)
        p+=2
    return ans

def sortArrayByParityII2(A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    i,j=0,1
    ans = [0]*len(A)
    for x in A:
        if x%2==0:
            ans[i]=x
            i+=2
        else:
            ans[j]=x
            j+=2

973. K Closest Points to Origin 最接近原点的 K 个点

解题思路:使用sorted排序 key为坐标平方和 取前K个

def kClosest(points, K):
    """
    :type points: List[List[int]]
    :type K: int
    :rtype: List[List[int]]
    """
    return sorted(points, key = lambda x:x[0]**2+x[1]**2)[:K]

977. Squares of a Sorted Array 有序数组的平方

解题思路:

def sortedSquares(A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    return sorted([x**2 for x in A])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值