Java基础算法每日5道详解(6)

news2025/2/24 10:27:07

112. Path Sum

路径总和

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

leetcode代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;

        if(root.left == null && root.right == null) return sum == root.val;

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

118. Pascal’s Triangle

帕斯卡三角

Given an integer numRows, return the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3Y9ZmRo5-1670866442793)(https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif)]

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

leetcode代码

class Solution {
     public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList();
        List<Integer> row = new ArrayList();
        for(int i = 0; i < numRows; i++) {
            for(int j = row.size() - 1; j >= 1 ; j--) {
                row.set(j, row.get(j) + row.get(j - 1));
            }
            row.add(1);
            res.add(new ArrayList(row));
        }
        return res;
    }
}

119. Pascal’s Triangle II

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pd0XqeQw-1670866488083)(https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif)]

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

leetcode代码

class Solution {
    public List<Integer> getRow(int k) {
        Integer[] arr = new Integer[k + 1];
        Arrays.fill(arr, 0);
        arr[0] = 1;

        for (int i = 1; i <= k; i++) 
            for (int j = i; j > 0; j--) 
                arr[j] = arr[j] + arr[j - 1];

        return Arrays.asList(arr);
    }
}

121. Best Time to Buy and Sell Stock

买卖股票的最佳时机

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

leetcode代码

class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE, max = 0;
        for (int i = 0; i < prices.length; i++) {
        min = Math.min(min, prices[i]);
        max = Math.max(max, prices[i] - min);
     }
     return max;
    }
}

125. Valid Palindrome

有效回文

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

leetcode代码

class Solution {
   public boolean isPalindrome(String s) {
    char[] c = s.toCharArray();
    for (int i = 0, j = c.length - 1; i < j; ) {
        if (!Character.isLetterOrDigit(c[i])) i++;
        else if (!Character.isLetterOrDigit(c[j])) j--;
        else if (Character.toLowerCase(c[i++]) != Character.toLowerCase(c[j--])) 
            return false;
    }
    return true;
  }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/151819.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

html+css实现一个响应式管理平台架构模板

文本将会带你使用htmlcss实现一个响应式的管理平台架构模板&#xff0c;目前来说市面上的管理平台架构模板大同小异&#xff0c;文本的知识点都会符合场景所需。 目录 1、管理平台的架构内容 2、顶部的布局 3、下半部分布局 4、左侧菜单区域实现 5、右侧主体区域实现 …

前端重新部署如何通知用户刷新网页?

我把我掘金的文章同步一份给CSDN 1.目标场景 有时候上完线&#xff0c;用户还停留在老的页面&#xff0c;用户不知道网页重新部署了&#xff0c;跳转页面的时候有时候js连接hash变了导致报错跳不过去&#xff0c;并且用户体验不到新功能。 2.思考解决方案 如何去解决这个问…

顶象助力绿球金科打造App低碳出行场景

“低碳出行”、“碳中和”、“碳惠普”正在成为近几年的科技热词之一。 自2020年9月&#xff0c;中国向世界许下“力争2030年前实现碳达峰&#xff0c;2060年前实现碳中和”的承诺以来&#xff0c;一场围绕绿色节能、低碳减排的变革正在席卷各行各业。 “碳中和”已经成为时代…

如何让SCI期刊审稿人,理解你的文章? - 易智编译EaseEditing

首先需要对论文进行全文润色 对于发表论文来说&#xff0c;进行润色是必须的&#xff0c;正因为SCI论文翻译要求高难度大&#xff0c;无论笔译还是口译都一定要有过硬的基本功&#xff0c;知识面要足够宽广&#xff0c;专业综合能力要求高。 所以当一篇论文的整体结构不到位&…

凯恩帝机床联网

一、设备信息确认 1、确认型号 数控面板拍照确认&#xff1a; 此系统为&#xff1a;K1TCi 注&#xff1a;凡是系统中带i的&#xff0c;基本上都含网口。 2、确认通讯接口 网口常见位置&#xff0c;XS92&#xff08;丝印标号&#xff09;&#xff0c;可通过这个确认&#x…

PnetLab模拟器安装锐捷镜像

安装准备&#xff1a; 1.安装完成pnetlab&#xff0c;这里不过多叙述&#xff1b; 2.在锐捷的网站下载好模拟器镜像&#xff08;目前只支持Switch和Router&#xff09;&#xff0c;下载地址&#xff1a;https://www.ruijie.com.cn/fw/wd/88899/ 官网下载后的内容包括下面几个…

Linux umount报错:device is busy

执行nfs卸载命令umount /mnt&#xff0c;报错target is busy. 或device is busy可以按以下步骤检查&#xff1a;退出要卸载挂载的目录&#xff0c;再执行卸载挂载cd ../umount /mnt找出占用目录的端口&#xff0c;kill端口fuser -m /mnt/kill -9 端口umount /mnt停止nfs服务&am…

计算机基础——操作系统

作者简介&#xff1a;一名云计算网络运维人员、每天分享网络与运维的技术与干货。 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a;网络豆的主页​​​​​​ 目录 前言 一.操作系统 1.操作系统简介 2.操作系统的主要功能 &#xff08;1&#xff…

【Kotlin】字符串操作 ② ( 字符串替换函数 replace | 字符串比较操作符 == 和 === | 字符串遍历 forEach )

文章目录一、字符串替换函数 replace二、字符串比较操作符 和 三、字符串遍历 forEach一、字符串替换函数 replace 字符串替换函数 replace 函数原型如下 : /*** 返回一个新字符串&#xff0c;通过替换此字符序列中匹配给定正则表达式的每个子字符串获得* 用给定的[替换]。**…

一个芯片工程师的ADC学习笔记 (二)

众所周知&#xff0c;ADC主要用于对模拟信号进行数字采集&#xff0c;以进行数据处理。我们周围的信号一般都是不断变化的模拟量&#xff0c;如光、温度、速度、压力、声音等。然而&#xff0c;我们大多数人都使用数字设备。如果我们想方便地使用和处理信息&#xff0c;就需要将…

【机器学习】关联规则挖掘算法 + 三大案例实战 + Apriori算法 + Python代码实现

文章目录一、关联规则概述1.1 关联规则引入1.2 关联规则相关概念介绍1.2.1 样本、事务、项集、规则1.2.2 支持度、置信度1.2.3 提升度1.2.4 所有指标的公式二、Python实战关联规则2.1 使用 mlxtend 工具包得出频繁项集与规则2.1.1 安装 mlxtend 工具包2.1.2 引入相关库2.1.3 自…

MP3解码算法原理解析

一&#xff1a;MP3编解码整体结构介绍 看懵逼了是吧。这里面有很多概念需要一一讲解。 比特流&#xff1a;比特流是一种内容分发协议。它采用高效的软件分发系统和点对点技术共享大体积文件&#xff08;如一部电影或电视节目&#xff09;&#xff0c;并使每个用户像网络重新分配…

记录--微信调用jssdk--Invalid Signature, updateAppMessageShareData: denied等问题

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 最近在做安卓内嵌入H5活动页拉新活动&#xff0c;遇到的棘手问题记录下&#xff0c; 一是为了日后遇到同样问题好回顾&#xff0c;二是希望能帮到有同样问题的兄弟。 废话不多说&#xff0c;先从最棘手…

【高阶数据结构】封装Map和Set

&#x1f308;欢迎来到数据结构专栏~~封装Map和Set (꒪ꇴ꒪(꒪ꇴ꒪ )&#x1f423;,我是Scort目前状态&#xff1a;大三非科班啃C中&#x1f30d;博客主页&#xff1a;张小姐的猫~江湖背景快上车&#x1f698;&#xff0c;握好方向盘跟我有一起打天下嘞&#xff01;送给自己的一…

蓝桥杯Python组排列和组合、二进制讲解

目录 一、排列 1、Python 的排列函数 permutations() 2、permutations() 按什么顺序输出序列&#xff08;重要⭐&#xff09; 3、易错点 二、组合 1、Python的组合函数combinations() 2、注意内容 三、手写排列和组合代码 1、手写排列代码&#xff08;暴力法&#xff…

【PWA学习】2. 使用 Manifest, 让你的 WebApp 更 Native

引言 我们知道&#xff0c;在 chrome(等一些现代浏览器)中&#xff0c;你可以将访问的网站添加到桌面&#xff0c;这样就会在桌面生成一个类似 “快捷方式” 的图标&#xff0c;当你点击该图标时&#xff0c;便可以快速访问该网站(Web App) 我们以 demo 为例&#xff0c;其添加…

无监督聚类表征学习方法之对比学习(Contrastive Learning)——simclr方法

无监督聚类表征学习方法之对比学习(Contrastive Learning)——simclr方法 1.参考论文 《A Simple Framework for Contrastive Learning of Visual Representations》 2.无监督聚类表征学习方法 主要有几种&#xff1a; ①自动编码器(AutoEncoder,AE); ②变分自编码器(Variatio…

两款开源.NET工作流引擎 Elsa 与ccflow使用比较

相对java开源的工作流程引擎.net开源的工作流程引擎相对较少&#xff0c;这里整理两款.net开源工作流引擎&#xff0c;做一下对比使用。elsa示例代码:Githubd地址&#xff1a;https://github.com/zhenl/MyElsaccflow下载地址&#xff1a;https://gitee.com/opencc/ccflowCCFlow…

Java笔记021-异常-Exception

异常-Exception看个实际问题和一段代码运行下面的代码&#xff0c;看看有什么问题->引出异常和异常处理机制package com12.exception_;/*** author 甲柒* version 1.0* title Exception01* package com12.exception_* time 2023/1/9 14:38*/ public class Exception01 {publ…

Mask RCNN网络源码解读(Ⅳ) --- Mask R-CNN论文解读

目录 1.Mask R-CNN简介 2.Mask分支 3.Mask R-CNN损失 4Mask分支预测使用 1.Mask R-CNN简介 回顾我们之前所说的图像分类、目标检测、语义分割的内容&#xff1a; 我们来看一下实例分割和语义分割的差别&#xff1a; Mask R-CNN不仅能够同时进行目标检测与分割&#xff0c;…