LeetCode Weekly Contest 127

数字政府政务服务AI大模型赋能智能体平台及AI场景应用规划方案(决策评审版).pptx 立即下载

第一次参加 LeetCode 的每周编程赛,排在 178 / 4682 ,还是可以接受的。(第一题交了次错答案罚时 5分钟真的伤不起啊不然都可以挺进前100了)

1、1005. Maximize Sum Of Array After K Negations

Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total. (We may choose the same index i multiple times.)

Return the largest possible sum of the array after modifying it in this way.

Example 1:

Input: A = [4,2,3], K = 1
Output: 5
Explanation: Choose indices (1,) and A becomes [4,-2,3].

题意

一个数组,进行 K 次操作(一次操作是对某个数正负取反,可以对同一个数进行操作),求操作后数组和的最大值。

解题思路

贪心法,对数组排序,先只对负数操作,从最小的开始。全操作完之后,如果K不剩,直接返回和;如果K还剩,说明此时已经全部转化为正数,那么对最小的正数操作。判断一下 K 是否是2的倍数来决定是否操作。

class Solution:
    def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
        A.sort()		# 排序
        target = -1
        for i, ele in enumerate(A):
            if K and ele < 0:
                A[i] = -A[i]
                target = i
                K -= 1
            else:
                break
              
        K = K % 2
        if K > 0:		# 需要对最小的正数取反,找到最小的正数
            if target+1<len(A) and A[target]>A[target+1]:
                A[target+1] = -A[target+1]
            else:
                A[target] = -A[target]
                
        return sum(A)

2、1006. Clumsy Factorial

Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.

For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.

Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.

Example 1:

Input: 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

题意

定义一个新的阶乘运算,依次使用 + - * / 几个符号,求最后结果。

解题思路

直接模拟这个运算,除了遇到减法要考虑到后面三个数字县做运算,其余符号直接按从左到右的顺序来计算即可。

class Solution:
    import math
    def clumsy(self, N: int) -> int:
        oper = 0
        ret = N
        N -= 1
        
        while N >= 1:		# N是当前要处理的数
            if oper == 0:	# *
                ret *= N
                oper = (oper+1)%4
                N -= 1
            elif oper == 1:     # /
                ret = math.floor(ret/N)
                oper = (oper+1)%4
                N -= 1
            elif oper == 2:		# +
                ret += N
                oper = (oper+1)%4
                N -= 1
            else:		# -
                if N >= 3:
                    ret -= (math.floor(N*(N-1)/(N-2)))
                    N -= 3
                    oper = 2		# 运算符变成 +
                elif N == 2:
                    ret -= 2
                    return ret
                elif N == 1:
                    ret -= 1
                    return ret
        return ret

3、1007. Minimum Domino Rotations For Equal Row

In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the i-th domino, so that A[i] and B[i] swap values.

Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.

If it cannot be done, return -1.

Example 1:

Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation: 
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

题意

两行数组,至少交换多少次,可以使得上面一行数组或下面的数组一行内内元素全相等。

解题思路

直接暴力枚举。假设最后调整之后一行内元素全为 K,枚举数组A的每个元素作为这个K的可能值,判断AB对应位置是否等于K来判断是否要进行交换操作。加入visit数组去重,加快查找速度。

class Solution:
    def minDominoRotations(self, A: List[int], B: List[int]) -> int:
        def tryswap(A, B):
            visit = []
            n = len(A)
            minSwapNum = 99999
            for i,ele in enumerate(A):
                if ele in visit:
                    continue
                visit.append(ele)		# 假设它是最后转化的结果
                swapNum = 0
                for j in range(n):
                    if A[j] == ele:
                        continue
                    elif B[j] == ele:
                        swapNum += 1
                    else:
                        swapNum = 99999
                        break
                minSwapNum = min(minSwapNum, swapNum)
            return minSwapNum
        
        swapNum = min(tryswap(A, B), tryswap(B, A))
        if swapNum == 99999:
            return -1
        return swapNum

4、1008. Construct Binary Search Tree from Preorder Traversal

Return the root node of a binary search tree that matches the given preorder traversal.

(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traversesnode.left, then traverses node.right.)

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

在这里插入图片描述

题意

根据先序序列重建二叉搜索树。

解题思路

先序序列第一个元素肯定是根节点。然后向后找到第一个大于它的元素的位置为K,那么list[1:K]是它的左子树,list[K:]是它的右子树,递归建树。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if len(preorder)==0:
            return None
        root = TreeNode(preorder[0])
        
        target = len(preorder)
        for i,ele in enumerate(preorder):
            if ele > preorder[0]:
                target = i
                break
        root.left = self.bstFromPreorder(preorder[1:target])
        root.right = self.bstFromPreorder(preorder[target:])
        
        return root
T18_低空经济示范区十五五通感一体化低空智联网与飞行服务保障体系设计方案_生态合作版.pptx 立即下载

相关推荐

基于深度学习的时间序列预测

深度学习在时间序列数据中应用广泛,学术界已经有很多深度学习模型来适应不同领域的时间序列数据集的多样性。那么到底有哪些基于深度学习的时间序列预测模型?他们的优缺点是什么?让我们一起来看一下。

Sharon0408的博客 6582

Leetcode进阶之路——Weekly Contest 127

1005. Maximize Sum Of Array After K Negations Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K tim...

MaloFleur 276

C++面向对象程序设计大作业:魔兽世界(三):开战

C++面向对象程序设计大作业:魔兽世界(三):开战问题描述问题分析代码 问题描述 问题来自于北京大学郭炜老师的C++慕课的大作业 魔兽世界的西面是红魔军的司令部,东面是蓝魔军的司令部。两个司令部之间是依次排列的若干城市,城市从西向东依次编号为1,2,3 … N ( N <= 20)。红魔军的司令部算作编号为0的城市,蓝魔军的司令部算作编号为N+1的城市。司令部有生命元,用于制造武士。 两军的司令部都会制造武士。武士一共有dragon 、ninja、iceman、lion、wolf 五种。每种武士都有

RedRum_1965的博客 4040

LeetCode笔记:Weekly Contest 297

LeetCode笔记:Weekly Contest 297

codename_cys的博客 190

【小贪】万字长文介绍因果推断和增益模型

本文首先从一个实例出发阐述了因果性不等于相关性,进而引出因果推断和增益模型。然后简单介绍了因果推断的基础内容,并介绍了主要的三类增益模型:元学习、增益直接建模、表示学习,每一类模型都简要介绍了其经典模型。之后介绍了增益模型的评价指标,包括uplift bins、uplift curve和qini曲线。增益模型实际上是一大类模型框架,本质上可以用传统响应模型或其他机器学习模型嵌入增益模型的框架,但是预测结果并不是一个概率,模型评价方式也有变化。训练样本收集增益模型建模强依赖于ab实验,数据要求很高。

打瞌睡_的博客 2506

LSTM模型 轨迹经纬度预测

原始时间序列数据如下所示,我们只取前两列纬度和经度作为输入数据 我们设定用前六个位置信息预测下一个位置,则两个样本的输入输出数据如下所示: 创建LSTM网络训练模型: import numpy as np from keras.layers.core import Dense, Activation, Dropout from keras.layers import LS...

Muzi_Water的博客 2万+

LeetCode笔记:Weekly Contest 344

LeetCode笔记:Weekly Contest 344

codename_cys的博客 510

深交所 vs 上交所:Level-2实时数据推送规则详解与策略适配指南

本文深度解析沪深Level-2实时数据推送规则的关键差异,包括逐笔成交、逐笔委托和10档行情接口的处理逻辑。针对高频交易策略,详细对比上交所与深交所在数据推送机制、时间戳处理及委托队列解析等方面的差异,并提供具体的策略适配方案和性能优化建议,帮助量化投资者提升跨市场交易稳定性。

weixin_27310417的博客 1173

LeetCode | 563. Binary Tree Tilt

Given a binary tree, return the tilt of the whole tree.The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree nod

pku_Coder的博客 1418

Delta并联机械手-Codesys实现以及正解逆解研究

由于Codesys的Robotics模块有Delta并联机械手的运动模型,因此借助Codesys的机械手运动模型,研究自己的正解逆解算法。

weixin_42386991的博客 5567

8.Python基础语法(五)续【光说不练假把式,上题】

Python基础语法(二) 有关于Python循环语句的几道实操,让大家理解知识点更深更透彻~

孤寒者的博客 2万+

LeetCode | 540. Single Element in a Sorted Array

540. Single Element in a Sorted Array DescriptionSubmissionsSolutions Total Accepted: 1638 Total Submissions: 2985 Difficulty:

pku_Coder的博客 1258

使用 MATLAB/Simulink 搭建一个步进电机细分控制系统的仿真模型

步进电机(Stepper Motor)是一种将电脉冲信号转换为角位移或线位移的执行元件,广泛应用于数控机床、3D打印、机器人、精密仪器等领域。其特点是开环控制、定位精度高、响应快、无累积误差。然而,传统步进电机在整步或半步运行时存在振动大、噪音高、转矩波动明显等问题。为了解决这些问题,细分控制技术被广泛采用。细分控制通过对绕组电流进行精确控制,使转子在两个整步之间实现平滑移动,从而提升电机的运行平稳性和位置精度。本教程将带你使用搭建一个步进电机细分控制系统的仿真模型,并通过仿真分析其。

amy_mhd的博客 430

LeetCode | 88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional

pku_Coder的博客 1112

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

LeetCode | 73. Set Matrix Zeroes

DescriptionGiven a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.Solution代码1:空间O(m + n),62 ms AC 将矩阵的0的状态存储在行列两个数组中class Solution { public: void setZeroes(vec

pku_Coder的博客 710

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode | 15. 3Sum(三数和为定值)

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.Note: The solution set must not contain duplic

pku_Coder的博客 701

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

LeetCode | 6. ZigZag Conversion(之字形变换)

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H N A P L S I I G Y

pku_Coder的博客 649

LeetCode | 60. Permutation Sequence——第K个全排列

The set [1,2,3,…,n] contains a total of n! unique permutations.By listing and labeling all of the permutations in order,We get the following sequence (ie, for n = 3):"123" "132" "213" "231" "312" "321"

pku_Coder的博客 639

LeetCode | 43. Multiply Strings(大整数乘法)

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.Note:The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Bo

pku_Coder的博客 591

LeetCode | 65. Valid Number

Validate if a given string is numeric.Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => trueNote: It is intended for the problem statement to be ambiguous. You should g

pku_Coder的博客 559

LeetCode | 56. Merge Intervals——合并区间

Given a collection of intervals, merge all overlapping intervals.For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].思路:按照start排序,然后遍历全部元素,如果完全错开就放进去,如果没有完全错开就修改上一区间的end值。用vector

pku_Coder的博客 537

LeetCode | 21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 合并两个有序链表.好久没有使用指针,对指针明显不太熟练了.所以看起来非常简单的题目,调试了好久,一直有指针相关错误.

pku_Coder的博客 488

LeetCode | Two Sum

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 ele

pku_Coder的博客 486

LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.For “(()”, the longest valid parentheses substring is “()”, which has

pku_Coder的博客 479

LeetCode | 89. Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray

pku_Coder的博客 471
上一篇: 商汤科技2018校招研究员笔试第一场
下一篇: [万能办法] Mac安装pkg包报错:安装失败 “安装器遇到了一个错误,导致安装失败,请联系软件制造商以获得帮助
PKU_CXK
博客等级 码龄10年 87粉丝 142原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值