【算法】力扣第 286 场周赛(最短代码)

文章目录

  • [5268. 找出两数组的不同](https://leetcode-cn.com/problems/find-the-difference-of-two-arrays/)
  • [5236. 美化数组的最少删除数](https://leetcode-cn.com/problems/minimum-deletions-to-make-array-beautiful/)
  • [5253. 找到指定长度的回文数](https://leetcode-cn.com/problems/find-palindrome-with-fixed-length/)
  • [5269. 从栈中取出 K 个硬币的最大面值和](https://leetcode-cn.com/problems/maximum-value-of-k-coins-from-piles/)
  • 总结

5268. 找出两数组的不同

一行,不用多说

class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        return[list(set(nums1)-set(nums2)),list(set(nums2)-set(nums1))]

5236. 美化数组的最少删除数

正向遍历即可,我写的四行解法

class Solution:
    def minDeletion(self, nums: List[int]) -> int:
        res, n, flag = 0, len(nums), 0
        for i, v in enumerate(nums):
            if not flag or v != pre:pre,res,flag = v,res+1,1-flag
        return n-res+1 if res % 2 else n-res

六弦爷一行解法

class Solution:
    def minDeletion(self, nums: List[int], c = 0) -> int:
        return len(nums) - reduce(lambda r, x: (r[0] + 1, x) if r[0] & 1 == 0 or r[1] != x else r, nums, (0, -1))[0] // 2 * 2

5253. 找到指定长度的回文数

先构造左边的回文数再反转,二行解法

class Solution:
    def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
        half,base = (intLength+1) // 2,10** ((intLength + 1) // 2 - 1)
        return [(func:=lambda q:-1 if len(left:= str(base + q - 1)) > half else int(left + ''.join(left[i] for i in range(len(left) - 1 - intLength % 2, -1, -1))))(q) for q in queries]

5269. 从栈中取出 K 个硬币的最大面值和

动态规划,c++六行解法

class Solution {
public:
    int maxValueOfCoins(vector<vector<int>>& piles, int k) {
        vector<int> dp(k + 1);
        for (auto &p: piles)
            for (int i = k; i >= 0; i--) 
                for (int j = 1, sum = 0; j <= p.size() && i >= j; j++) 
                    {sum += p[j - 1];dp[i] = max(dp[i], dp[i - j] + sum);}
        return dp[k];
    }

};

总结

T2有坑,T4用python可能TLE。。。
T1+T2+T3+T4共1+1+2+6=10行代码,完成【20行完成周赛】的目标!

你可能感兴趣的:(python基础,leetcode,算法,职场和发展,python,c++)