leetcode-top 100 liked questions-python

这篇博客列举了LeetCode中最受欢迎的12个问题,包括字符串查找、数组操作、二叉树遍历和深度优先搜索等。通过Python解决这些问题,强调了二叉树的遍历策略和数组处理技巧,例如:寻找数组中的所有回文子串、查找丢失的数字、计算二叉树直径等。每个问题都提供了详细的解释和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
找出字符串中,字串与p字符分布相同,但是顺序可以不同的字串的开始下标,核心思想是使用滑动窗口

2、Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

找出数组中缺失的数字,不使用外部的存储空间,数组中值的范围在长度以内

注意看这题数组元素的值全都在数组索引的范围内,那么肯定就是套用那个经典的给元素值赋正负来表达额外信息的套路了。而这题就是遍历每个元素,把与元素值相等(实际差个1)的那个索引对应的元素赋值为负数,然后遍历一遍完成后,再次遍历,如果某个索引对应的元素值是正数,就说明与这个索引相同的值在数组中不存在,就是结果了。

[4,3,2,7,8,2,3,1]演示一遍过程:

[ 4,  3,  2,  7,  8,  2,  3,  1] -> [ 4,  3,  2, -7,  8,  2,  3,  1]
[ 4,  3,  2, -7,  8,  2,  3,  1] -> [ 4,  3, -2, -7,  8,  2,  3,  1]
[ 4,  3, -2, -7,  8,  2,  3,  1] -> [ 4, -3, -2, -7,  8,  2,  3,  1]
[ 4, -3, -2, -7,  8,  2,  3,  1] -> [ 4, -3, -2, -7,  8,  2, -3,  1]
[ 4, -3, -2, -7,  8,  2, -3,  1] -> [ 4, -3, -2, -7,  8,  2, -3, -1]
[ 4, -3, -2, -7,  8,  2, -3,  1] -> [ 4, -3, -2, -7,  8,  2, -3, -1]
[ 4, -3, -2, -7,  8,  2, -3,  1] -> [ 4, -3, -2, -7,  8,  2, -3, -1]
[ 4, -3, -2, -7,  8,  2, -3,  1] -> [-4, -3, -2, -7,  8,  2, -3, -1]

output: [5, 6]

3、Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.


4、 Convert BST to Greater Tree

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13

如果我们按照中序遍历的逆序,即先右子节点,再父节点,最后左子节点顺序遍历的话,刚好就能降序地访问每一个节点。比如例子中就会是以13,5,2的顺序访问,这样我们每访问一个节点,就记录下到该节点的和,并在访问下一节点时将该和值加到节点的值上。以例子说明: 
初始sum为0。 
访问到13,更新节点值为13+sum=13+0=13,sum更新为sum+13=0+13=13; 
访问到5,更新节点值为5+sum=5+13=18,sum更新为sum+5=13+5=18; 
访问到2,更新节点值为2+sum=2+18=20,sum更新为sum+2=18+2=20;

因此,题目其实考的就是BST中序对应的逆序遍历,先访问右子树,然后父节点,最后左子树,并在访问过程中记录已访问的节点总和,累加到当前的节点上。


5、Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longestpath between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree 

          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

计算子树的深度


6、Subtree of Another Tree

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return  true , because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2

Return false.

判断树t是否是树s的子树,要注意树序列化时要增加一些分隔符


7、Shortest Unsorted Continuous Subarray

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order

升序的数组中,找到最短的无序的数组,并返回长度

题目标签:Array

  题目给了我们一个nums array, 让我们找出一个最短的无序连续子数组,当我们把这个子数组排序之后,整个array就已经是排序的了。

  要找到这个子数组的范围,先要了解这个范围的beg 和 end 是如何定义的。

  来看这个例子:1 3 5 7 2 4 5 6

  a. 当我们找到第一个违反ascending 排序的数字 2的时候,我们不能是仅仅把beg 标记为2的前面一个数字7,而是要一直往前,找到一个合适的位置,找到在最前面位置的比2大的数字,这里是3。

  b. 同样的,为了找end, 那么我们要从7的后面开始找,一直找到一个最后面位置的比7小的数字,这里是6。

  这样的话,范围就是3到6 是我们要找的子数组。把3到6排序完了之后,整个array 就已经是排序的了。

 

  这里我们可以发现,2是min, 7是max,所以我们可以分两个方向来分别寻找beg 和end。

  从右到左(绿色),维护更新min 和 beg;

  从左到右(红色),维护更新max 和 end。

8、Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

Note: The merging process must start from the root nodes of both trees.

合并两棵树,则合并后的节点值为原来的树对应位置的两个节点的和

考察的就是二叉树的遍历,遍历每个结点然后如果重叠(两个二叉树结点都不为空)新结点值便为两者和,不重叠(只有一个结点为空)新结点值为不为空的值,全为空到达底部返跳出。按照这个逻辑进行迭代
联想:二叉树遍历方式有深度优先和广度优先,深度(纵向)优先在Python中一般使用列表,广度优先(横向)一般使用迭代


9、3Sum

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

找出数组中加和为0的数的组合


10、Combination Sum

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]

]

给定一个候选列表,输出加和为目标值的组合,数值可以重复,但组合不可以重复

11、Jump Game

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

题意:

给你一组正整数,数组里面数字表示该位置可以跳多少步。如果从第一个跳到最后那个数,就返回成功否则返回失败。

 

比如说A =[2,3,1,1,4]

默认位置为A[0],

方案一:A[0]往后最多跳2步--->A[2],A[2]能往后最多跳1步--->A[3],A[3]能往后最多跳1步--->A[4].(到了最后一个,无论该位置是多少都是True)

方案二: A[0]能往后跳1步--->A[1],A[1]跳3步--->A[4]

比如A = [3,2,1,0,4]

从默认位置A[0]能往后跳3步--->A[3],A[3] = 0也就是只能往后0个,不能到最后。经过多次尝试发现,无论如何不能到最后,则返回false

思路:

遍历数组,剩余步数step不为零的前提下,每次向前移动一步,将当前的num[i]和step相比较取较大者,作为剩余步数step。


12、Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
给定一个m×n的非负矩阵,每个位置(i,j)只能向下和向右),然后找到一条路使得从(0,0)到(m - 1,n - 1)经过的所有数字的和最小。

思路:这个题也是最短路径的变形题,除了第一行和第一列,每个点都要找它上面和左面的小的那个加。

动态规划公式为:MPS[i][j] = Min(MPS[i-1][j],MPS[i][j-1])+ val[i][j]


13、   Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

在给定的字母板上寻找给定的单词,单词要用相邻单元重建,相邻意味着从一个字母开始垂直或者水平方向上开始寻找,同一个位置的字母只能访问一次




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值