查看: 8481| 回复: 33
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题打卡贴

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
自己刷题的效率实在太低,外加懒癌和拖延症晚期,迟迟也没动手。现在过完年了也该开始了,开贴打卡提升效率,本人背景工作3年多准备下月准备开始面试,以前刚毕业刷过350题左右,但是leetcode现在已经1000题了。
但是题多不代表题的类型增加了,所以这一个月的计划主要刷完前450题的重要高频题目,熟悉各种题型的解题思路,然后下个阶段在重点按公司和面经准备。
按个人以前的经验,刷题主要靠总结,因为学习的本质就是刻意重复练习,如果为了完成任务赶进度,发现回来都不记得题目刷过。其实和我们以前背单词也类似,做过的题要定期复习,所以开贴打卡还要把思路写一下,
定期回来看看自己以前解的题,巩固复习的同时有时候可能还有新思路。这次刷题按照分类来刷,有利于对特定题目加强解题的思路。
第一天刷string类型的题,比较基础,先热热身,做了10多道,明天再接再厉。
#
名称
Tag& 频率
题目
解题
28
string
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
热身题,遍历一遍,截取子串对比就行
14
string
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input:["flower","flow","flight"]
Output: "fl”
从一个数组里找字符串的公共最长前缀。
最直接的方法就是,选取第一个字符串,从中一个个拿出字符来。
然后在和数组里面每个字符串相对的位置进行比较,
当被对比的字符串长度小于当前index或者两个字符串相应位置字符不一致,
就返回当前前缀
58
string
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Example:
Input: "Hello World"
Output: 5
非常简单,记得要strip掉字符前后的空格,len(s.split()[-1])
387
string
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
总共就26个字母,然后数一下每个字符在字符串出现次数,
等于1就把index加到我们结果数组中,最后返回最小indx
383
string
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
建立两个数组,分别count里面字母出现次数,
最后比较两counter里面字符出现次数,
如果当前ransomNote字符次数大于magazine该字符出现字符返回false
344
string
two-pointer
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
two pointer入门题
151
string
Given an input string, reverse the string word by word.
Example:  
Input: "the sky is blue",
Output:"blue is sky the".
这题考对数组和字符的基本操作,需要熟悉数组字符串的一些基本方法,
比如strip(), reverse(), split(), join()
186
string
two-pointer
Given an input string, reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output:["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
输入从字符串变成了字符数组,思路是写个two-pinter的反转方法。
先把数组反转,然后从头到尾一个个字反转。
345
string
two-pointer
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input:"hello"
Output:"holle”
要求交换字符串里面的原音字母,two pointer解法,两端往中间遍历,2个case
  • 如果都是原音则交换,

  • 一边为原音就只移动另一端直到遇到原音

记得把字符转化成数组,string是imutable的
205
string
HashMap
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t ="add"
Output: true
Example 2:
Input: s = "foo", t ="bar"
Output: false
简单说题意就是要把s里面的字符与t里面的一一对应起来,
如果有一对多或者多对一的情况都返回false。
解题:同时遍历两个数组,用map来存字符映射,
如果发现一对多(当前t和存到映射的不符)或者
多对一(当前t已经在映射的值里面)返回false。
293
string
Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.
Input: s = "++++"
Output:
[
  "--++",
  "+--+",
  "++--"
]
一次要翻转两个连续的加号为减号,问就反转一次所有的反转可能结果。
遍历一遍,反转相邻的两个相同的加号为减号然后加到结果即可。
294
string
backtracking
Write a function to determine if the starting player can guarantee a win.
Example:
Input: s = "++++"
Output: true
Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".
这次问第一次下的玩家能否赢,这种类型一看就要枚举所有可能,
用backtracking做,看第二个玩家能否赢,不能的话就返回true。

290
string
HashMap
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
这题和上面205如出一辙,只是把字符映射换成字符-单词映射,思路一样。
242
string
HashMap
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
这题有多种解法,第一你可以sort两个字符串,然后比较,时间复杂度o(nlogn)
第二用计数法,用map存两个字符串字符出现次数,最后对比是否相等。
49
string
HashMap
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
要求将anagrams归类,用一个map,用排序后的单词做key,value是一个空数组。
遍历数组,把排序后的单词放到对应key的数组里。
249
string
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
这题大体思路和上一题类似,就是要求找出shift pattern一样的字符串,
我们就可以用字符本身对应的unicode, 算出一个字符串的对应patten,
比如’abc’就是[1, 2], 因为b到a距离为1,c到a距离为2。
然后用这个pattern作为map的key,value为一个数组包含
所有符合pattern的字符串。




评分

参与人数 1大米 +3 收起 理由
ak47rick + 3 给你点个赞!

查看全部评分


上一篇:在职刷题 发篇战拖监督一下自己
下一篇:东湾Fremont fulltime刷题求队友
推荐
 楼主| creazy-lobster 2019-3-8 15:58:35 | 只看该作者
全局:
第十三天,数组类。

243
Array
L家中低频
Given a list of words and two words word1 and word2,
return the shortest distance between these two words in the list.
要求找两个单词在数组里面的最小距离,单词可能有重复。
设置两个index当遇到要找的单词就更新index,算距离更新结果就好。
244
Array
L家中频
Design a class which receives a list of words in the constructor,
and implements a method that takes two words word1 and word2 and
return the shortest distance between these two words in the list.
Your method will be called repeatedly many times with different parameters.
上一题的follow up,现在要求写个class,如果用上一题方法也可解,就是太慢了。
优化方法就是在初始化的时候建一个map,把单词和其对应的位置们建立映射。
然后在寻找距离的方法里面,我们取出两个单词的位置数组,从头开始遍历,
每次计算更新当前最短距离。
另一个优化就是我们比较完了后移动2个单词当前位置较小的一个
例子’cat’:[3], ‘bot’:[1,2,5, 6, 7], 我们能看到cat的index为3,所以
前2次比较会移动bot的index,直到5>3的时候我们移动‘cat’发现到达终点
结束遍历,因为6,7的距离不用比较也知道不会比5到3的距离短。
245
Array
L家低频
Given a list of words and two words word1 and word2,
return the shortest distance between these two words in the list.
word1 and word2 may be the same and
  they represent two individual words in the list.
现在给的两个单词可能是一样的,我们只需要在第一题的解题上加一个判断,
就是当找到第二个单词的时候,我们判断两个单词是否相等,
如果相等就把idx1 = idx2, 然后idx2 = i, 这样idx1就是单词的前一个位置。

217
Array
低频
Given an array of integers, find if the array contains any duplicates.
Ex:
Input: [1,2,3,1]
Output: true
简单判断下数组里面是否有重复。暴力解法O(n^2), 把所有pair找出来对比。
第二种解法把数组排序,然后从头开始对比,时间复杂度O(nlogn)
第三种解法用set的话可以做到时间空间复杂度O(n)。
219
Array
低频
Given an array of integers and an integer k, find out whether there are two distinct
indices i and j in the array such that nums = nums[j]
and the absolute difference between [i]i
and j is at most k.
Ex:
Input: nums = [1,2,3,1], k = 3
Output: true
[/i]
上题follow up, 问数组里有没有相同的两个数之间的index距离小于等于k。
这样的话我们就需要记录数上一次出现的index了,所以这题用map,
key为数字,value为上一次出现的index,
所以当找到相同数字时候一减就知道是否小于k了,
注意大于k的话要把数字map里的值更新为当前index作为下一次对比起点。
220
Array
低频
Given an array of integers, find out whether there are two distinct indices i and j
in the array such that the absolute difference between nums and nums[j]
  is at most [i]t
and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
[/i]
这题要求找出数组中两个数,满足2个条件,1:两个数值相差不超过t,
2:两个数的坐标相差不超过k。所以我们可以想到要维护一个长度k的窗口。
也可以看成桶排序,桶宽度为t+1,如果有两个数差值不大于t,那么要么
是当前桶里面,要么是前后两个桶里面。
55
Array
中频
Given an array of non-negative integers, you are initially positioned at the first
index of the array. Each element in the array represents your maximum jump
length at that position.
Determine if you are able to reach the last index.
Example:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
要求能不能跳到最后一个index,我们只需要保存当前能跳到的最远距离,
一次遍历之后就知道能不能跳到最后一个位置了。
就拿例子来说,遍历第一个值2,所以可以跳到最远为index 2。
遍历第二个数为3,首先检查当前index是否在能跳到的距离内,
(如果第一个数0, 能跳到最远距离到不了这里就不行),
如果可以就更新最远能跳到index 为3+1 = 4,以此类推。
45
Array,
BFS,
Greedy
中频
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.
jump game follow up,要求最少次数的jump到达最后index,
注意他assume you can always reach last index. 这题可以用bfs, 贪心解决。
这里用了贪心算法,主要思想是维护一个当前最远能跳到的window,
遍历过程中不断更新能跳到最远的index,比如例子第一个位为2,
当遍历到当前window最后一位2的时候就必须要jump了,
然后更新window的右边界为当前最远index,
这里最远就是window里面能跳到到最远距离,
以此下去就是到最后一位到最短跳数。
121
Array
超高频
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction
(i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Ex:
Input: [7,1,5,3,6,4]
Output: 5
买卖股票第一题,只能做一次transacton,求最大profit。
我们知道求最大profit其实是求股票中一个波峰和一个波谷最大到差值。
由于要低价买高价出,我们需要找波谷波峰,
所以在遍历过程中我们首先需要一个变量存当前最小值(波谷)。
然后在遍历过程中,不断更新当前能赚到到max profit,最后既能得到最大profit。
122
Array
中频
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
  (i.e., buy one and sell one share of the stock multiple times).
Ex:
Input: [7,1,5,3,6,4]
Output: 7
第二题可以做任意多次交易,这次其实是求所有从波谷到波峰到差值到和。
我们只需要在遍历过程中在单调递增到时候把profit加入总profit就好了。
123
Array,
DP
低频
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Ex:
Input: [3,3,5,0,0,3,1,4]
Output: 6
第三题,最多交易两次,也就是说两次交易间有一分界线,
分界线左右是各自的最大利润,所以只要从左到右,从右到左计算出当前最大利润,找到那条分界线让两边利润加起来最大就可。
首先我们把第一题用到技巧拿来track maxprofits, 如下
input:       [3,3,5,0,0,3,1,4]
maxPro    [0,0,2,2,2,3,3,3]
然后从后往前遍历, curMax记录当前遇到最大值, maxPro记录当前最大profit
curMax    [5,5,5,4,4,4,4,4]
maxPro    [4,4,4,4,4,3,3,0]
最后两个maxpro数组对应index加起来最大到和为2次transaction最大收益。
188
Array
低频
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
第四题,要求在给定最多k次交易的条件下找出最大收益。
dp解法,把问题分解为subproblems,  dp[j]为第j天做最多i次交易的最大收益。
我们先思考下,要求第j天最大收益,在第j天我们有卖或者不卖两种骚操作,
我们取其中较大的作为这天的最大收益。
然后有dp[i][j] = max(
                                   1. 第j天不做交易的最大profit: dp[i][j-1]         
                                   2. 第j天做交易的最大profit: max(
                                           prices[j] - princes[m] + dp[i-1][m]    (m from 0 to j-1)
                                           第m天买入第j天卖出收益+第m天卖出时最大收益
                                  )
                        )
例子[2, 5, 7 ,1, 4, 3, 1, 3], k = 3
初始化dp数组,第一行第一列为0,因为只有1天不可能做交易,
0次交易也不会有收益。
i    0   1   2   3   4   5   6   7
     2   5   7   1   4   3   1   3
     ---------------------------
0|  0   0   0   0   0   0   0   0
1|  0   0   0   0   0   0   0   0
2|  0   0   0   0   0   0   0   0
3|  0   0   0   0   0   0   0   0
完成第一行后,也就是最多1次交易后
i    0   1   2   3   4   5   6   7
     2   5   7   1   4   3   1   3
     ---------------------------
0|  0   0   0   0   0   0   0   0
1|  0   3   5   5   5   5   5   5
2|  0   0   0   0   0   0   0   0
3|  0   0   0   0   0   0   0   0
比如求dp[1][2]时候,就是求前2天交易1次最大第收益,所以我们先分别算从0天到1天时候买入,第2天卖出的收益加上i-1=0天的最大收益如下,由于0天没有收益所以前一天最大收益都为0,然后m=0也就是0天买入第2天卖出收益最大为5。再算dp[i][j-1] = dp[1][2-1] = 3,就是第2天不做交易时候最大收益,然后5 大于 3所以第二天卖出第0天买入为当前最大收益.
dp[i][j] = max(
                                   dp[i][j-1]         第j天不做交易的最大profit
                                   max(
                                           m = 0: 7-2+0=5
                                           m = 1: 7-5+0=2
                                  )
                        )
[/i][/i][/i][/i][/i]




回复

使用道具 举报

推荐
 楼主| creazy-lobster 2019-3-12 14:53:34 | 只看该作者
全局:
第十六天,数组类里面的sliding window,还有prefix sum

239
Array
SlidingWindow
近期高频

Given an array nums, there is a sliding window of size k which is moving from
the very left of the array to the very left. You can only see the k numbers in
  the window. Each time the sliding window moves left by one position.
  Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output:[3,3,5,5,6,7]
Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
1 [3  -1  -3] 5  3  6  7       3
1  3 [-1  -3  5] 3  6  7       5
1  3  -1 [-3  5  3] 6  7       5
1  3  -1  -3 [5  3  6] 7       6
1  3  -1  -3  5 [3  6  7]      7
这题给定一个数组和一个window的长度,窗口从头移动到尾,
要求返回一个数组包含了每个窗口的最大值。这题解法是使用双端队列,
主要思路就是我们把当前窗口最大值放在deque最左边,当窗口要移动的时候就把最左边的值
拿出来当作当前窗口的最大值加入结果中。
从头遍历数组,4个操作:
  • 当deque里面最左边的数超出了window的范围就移除,保证deque里面的数在window里面

  • 如果当前数组的值num大于deuqe最右边的值,就移除掉deque右边的值直到deque最右边大于等于当前num或者为空。这一步保证了deque最左边的值为当前窗口最大值。

  • 然后把当前值加入deque

  • 把deque最左边当前窗口最大值加到结果去


例子: [1, 3, -1, -3, 5, 3, 6, 7]
i = 0    dq = [1]             result = []      dq为空,跳过第1,2步  
i = 1    dq = [3]             result = []     3大于1,移除1
i = 2    dq = [3, -1]        result = [3]     -1不大于dq最右边数, 当窗口长度等于k时开始加到结果
i = 3   dq = [3, -1, -3]    result = [3, 3]     -3不大于dq最右边数, 加当前最大值3
i = 4   dq = [5]               result = [3,3,5]     dq最左边3超出window移除,dq从右到左最右边数比5小
i = 5   dq = [5, 3]           result = [3,3,5,5]     5在当前window且3不大于dq最右边
i = 6   dq = [6]               result = [3,3,5,5,6]     6比dq从右到左所以数都大
i = 7   dq = [7]               result = [3,3,5,5,6,7]     7比dq从右到左所以数都大
有一点要注意就是这里演示方便用的值,其实我们要存index到dq,
才好检查他是否在当前窗口里面。
295
Array
heap
近期高频
Median is the middle value in an ordered integer list. If the size of the list is even,  there is no middle value.
So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
  • void addNum(int num) - Add a integer number from the data stream to the data structure.

  • double findMedian() - Return the median of all elements so far.


Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
这题要设计寻找当前数据的中位数的方法,
一个用来往里面加数,一个用来返回当前中位数。
思路其实挺简单,就是用两个堆,分别用来存小的和大的部分,
然后返回中位数的时候只需检测两个堆长度是否相等,
如果相等就返回小的部分的最大值和大的部分最小值的平均值,
不相等就返回大的部分的最小值。实现的话取决于语言,java可以维护最大堆和最小堆,
python默认最小堆要维护一个最大堆就把数取负放进去。
53
Array
DP
prefix sum
高频
Given an integer array nums, find the contiguous subarray
which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
从一个数组中找子数组使其组成的和最大, 这题首先需要算当前子数组的和,
就是说要控制子数组的window,如何控制呢?
遍历过程就是窗口右边界, 关键在何时移动左边界,
每一次右指针移动我们就比较当前window里面数的和与当前数的大小,当前数大,
说明前面window子数组和还没有当前的大爷大,所以窗口左指针移动到你大爷这,
然后继续看下一个。
这题使用一个一位数组,dp 表示i这个位置子数组能取到最大的和。优化一下我们可以不用数组达到O(1) space, 稍微看一下知道我们只需要记录前一位子数组和就好了。
325
Array
prefix sum
HashTable
低频
Given an array nums and a target value k,
find the maximum length of a subarray that sums to k.
If there isn't one, return 0 instead.
Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
和two sum类似,运用prefix sum的思路来确定子数组和。公式如下,
preSum[0:i] = preSum[i:n] - k
例子:       [1, -1, 5, -2, 3]   k=3
prefixsum [1, 0,  5,  3,  6]
map     [1:0, 0:1, 5:2, 3:3, 6:4]
index为3时候,取prefix sum为3-3=0的index截取子数组,更新长度。
209
Array
sliding window
中频
Given an array of n positive integers and a positive integer s,
find the minimal length of a contiguous subarray of which the sum ≥ s.
If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
求最短的子数组,其和大于等于给定s的值。然后还是sliding window和prefix sum。
解体思路就是维护一个窗口,当前窗口和小于s时候,移动右指针;
当窗口和大于等于s时候,先跟新最短长度,然后移动左窗口直到小于s。
238
Array
超高频
Given an array nums of n integers where n > 1,  return an array output such
that output is equal to the product of all the elements of nums except nums[i].
Example:
Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O([i]n
).
[/i][/i]
要求数组中每个数除开自己的所有数的乘积,不让用除法,所以得另外想办法。
思路还是从prefix product开始,我们可以看出这样可以得到每个数左边乘积的一个数组,
同理我们可以算出每个数右边数的乘积,然后把两个乘积乘起来就是除开自己的所有数乘积。
nums           #1 , 2, 3, 4
左边乘积      #1 , 1, 2, 6

nums           #1  , 2,   3,  4
右边乘积      #24, 12, 4,  1
152
Array, prefixsum
中频
Given an integer array nums, find the contiguous subarray within an array
(containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
要求找出子数组的最大乘积,这题有负数。
这题思路和上题类似,也是算出左右prefix product,我们可以看出最大值为6,
当然解体时只需一个变量保存当前最大值就好了,不用开数组。
nums      #2,      3,      -2,        4
左边乘积 #2,      6,      -24,   -96
右边乘积 #-96,  -24,   -8       ,4
这题还有一个trick,就是0出现的时候,你后面子数组乘积就全为0了,所以我们遇见0了以后要从新计算乘积。
228
Array
Capital one高频
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
在排序数组里面找出连续的数字的起始和终止位置,比较简单,
遍历数组检测是否连续,连续就继续,不连续就把当前窗口左右边界加入结果,
移动窗口到当前位置。
163
Array
G家中低频
Given a sorted integer array nums, where the range of elements are
in the inclusive range[lower,upper], return its missing ranges.
Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]
和上面一题差不多,用个pre变量记录当前range的起始,
需要检测pre和当前值的距离,一个数和大于1个数调整输出格式就好。



回复

使用道具 举报

推荐
 楼主| creazy-lobster 2019-3-23 15:17:39 | 只看该作者
全局:

第22天
203Remove Linked List ElementsLinkedList
AGPY低频
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
移除链表里面给定的val,这题也需要dummy node,
因为可能第一个就是要移除对象。然后设置pre,cur一前一后,
每次移动cur如果cur.val == val就把pre的next指向下一个,else移动pre。
82Remove Duplicates from Sorted List IILinkedList
salesforce
Google低频
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
要求删除所有重复的数字,只留下没有重复的数字。
同样的套路,dummy node,当发现cur和下一个元素重复的话,
我们就一直寻找最后一位,然后把pre的next指向下一个元素。
369Plus One Linked ListLinkedList
Google,Amazon低频
Given a non-negative integer represented as non-empty
a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero,
except the number 0 itself.
The digits are stored such that the most significant digit is
at the head of the list.
Example :
Input: [1,2,3]
Output: [1,2,4]
这题如果不做限制用stack,要求O(1)space的用以下思路:
分2部:第1部用left,right两个变量做标记,right指向head,遍历到最后,
当right不为9的时候,就把left=right,
这样保证了left是需要进位的最前面那位,
比如1→9→9→9, 最后i指向1,j指向最后。
第二步因为right指向最后位,我们看right是否为9,
不为9直接加1不会进位。
是9的话我们就把i+1然后把i后面的数全部设为0就好。ex: 2→0→0→0
还有1种case需要注意就是9→9这种,这种情况需要返回dummy node
2Add Two NumbersLinkedList
Amazon
Google
Facebook
Microsoft
Apple
Yahoo
其他多公司低频
You are given two non-empty linked lists representing two
non-negative integers. The digits are stored in reverse order and
each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
这题要求两个链表代表的数字加起来的和的一个新链表,表的数字的倒序的
和其他链表题一样我们需要个dummy node来创建新表,
首先我们需要一个carry变量来存进位,
然后遍历l1, l2,分别把他们的值和carry加入sum变量,
然后我们用除法取模的方法,比如sum=4+6=10, carry = sum//10
newNode.val = sum%10,这样就跟新了carry,创建了当前节点。
然后接着做下一个节点,注意l1, l2可以为空,carry可以为0,
所以当l1, l2其一不为空或carry为1时候都要创建新node。
445Add Two Numbers IILinkedList
AGFM低频
You are given two non-empty linked lists representing two
non-negative integers.
The most significant digit comes first and each of their nodes
contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Follow up:
What if you cannot modify the input lists?
In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
上一题变形题,现在数字是正序的
用了2个stack可以从后往前拿数,其他的和上一题步骤差不多。
160Intersection of Two Linked ListsLinkedList
AGUFM低频
Write a program to find the node at which the intersection of
two singly linked lists begins.
https://assets.leetcode.com/uploads/2018/12/13/160_statement.png
要求两个有相交的linkedlist的交点,例子如下就是找到8。
4(a)→1\
8→4→5
5(b)→0→1/
思路很巧妙,循环2遍,用a,b指针分别指向两个链表head,
然后遍历,直到最后然后把指针指向另一个链表头部,
直到他们相遇。
比如例子a=4,b=5, 当a=null时候,a就指向5。
下一步当b=null当时候,b指向4,a指向0,
你会发现他们在移动2步就会相遇。
4(b)→1\
8→4→5
5→0(a)→1/
当两个链表没有交点的时候,两次循环后他们会同时停在null位置上
从而推出循环
21Merge Two Sorted ListsLinkedList
Amazon高频
多公司低频
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
合并两个链表,比较基础,dummy node创建新链表,
然后当两个链表都不为空都时候往里面加小的,
最后当剩下一个链表当时候把他加到后面就好了。
[/table][table]
203Remove Linked List ElementsLinkedList
AGPY低频
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
移除链表里面给定的val,这题也需要dummy node,
因为可能第一个就是要移除对象。然后设置pre,cur一前一后,
每次移动cur如果cur.val == val就把pre的next指向下一个,else移动pre。
82Remove Duplicates from Sorted List IILinkedList
salesforce
Google低频
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
要求删除所有重复的数字,只留下没有重复的数字。
同样的套路,dummy node,当发现cur和下一个元素重复的话,
我们就一直寻找最后一位,然后把pre的next指向下一个元素。
369Plus One Linked ListLinkedList
Google,Amazon低频
Given a non-negative integer represented as non-empty
a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero,
except the number 0 itself.
The digits are stored such that the most significant digit is
at the head of the list.
Example :
Input: [1,2,3]
Output: [1,2,4]
这题如果不做限制用stack,要求O(1)space的用以下思路:
分2部:第1部用left,right两个变量做标记,right指向head,遍历到最后,
当right不为9的时候,就把left=right,
这样保证了left是需要进位的最前面那位,
比如1→9→9→9, 最后i指向1,j指向最后。
第二步因为right指向最后位,我们看right是否为9,
不为9直接加1不会进位。
是9的话我们就把i+1然后把i后面的数全部设为0就好。ex: 2→0→0→0
还有1种case需要注意就是9→9这种,这种情况需要返回dummy node
2Add Two NumbersLinkedList
Amazon
Google
Facebook
Microsoft
Apple
Yahoo
其他多公司低频
You are given two non-empty linked lists representing two
non-negative integers. The digits are stored in reverse order and
each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
这题要求两个链表代表的数字加起来的和的一个新链表,表的数字的倒序的
和其他链表题一样我们需要个dummy node来创建新表,
首先我们需要一个carry变量来存进位,
然后遍历l1, l2,分别把他们的值和carry加入sum变量,
然后我们用除法取模的方法,比如sum=4+6=10, carry = sum//10
newNode.val = sum%10,这样就跟新了carry,创建了当前节点。
然后接着做下一个节点,注意l1, l2可以为空,carry可以为0,
所以当l1, l2其一不为空或carry为1时候都要创建新node。
445Add Two Numbers IILinkedList
AGFM低频
You are given two non-empty linked lists representing two
non-negative integers.
The most significant digit comes first and each of their nodes
contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Follow up:
What if you cannot modify the input lists?
In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
上一题变形题,现在数字是正序的
用了2个stack可以从后往前拿数,其他的和上一题步骤差不多。
160Intersection of Two Linked ListsLinkedList
AGUFM低频
Write a program to find the node at which the intersection of
two singly linked lists begins.
https://assets.leetcode.com/uploads/2018/12/13/160_statement.png
要求两个有相交的linkedlist的交点,例子如下就是找到8。
4(a)→1\
8→4→5
5(b)→0→1/
思路很巧妙,循环2遍,用a,b指针分别指向两个链表head,
然后遍历,直到最后然后把指针指向另一个链表头部,
直到他们相遇。
比如例子a=4,b=5, 当a=null时候,a就指向5。
下一步当b=null当时候,b指向4,a指向0,
你会发现他们在移动2步就会相遇。
4(b)→1\
8→4→5
5→0(a)→1/
当两个链表没有交点的时候,两次循环后他们会同时停在null位置上
从而推出循环
21Merge Two Sorted ListsLinkedList
Amazon高频
多公司低频
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
合并两个链表,比较基础,dummy node创建新链表,
然后当两个链表都不为空都时候往里面加小的,
最后当剩下一个链表当时候把他加到后面就好了。
回复

使用道具 举报

🔗
John0773 2019-2-17 16:32:07 | 只看该作者
全局:
正好也在刷第三道。加油 加米不扣米 正好还差一点才看得到帖子 大方撒点米贝
回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-2-18 15:26:13 | 只看该作者
全局:
第二天打卡,接着刷字符串类型。发现昨天的表格全部右对齐了,写的时候明明没有额
#
名称
Tag& 频率
题目
解题
87
string
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
    rgeat
   /    \
  rg    eat
/ \    /  \
r   g  e   at
           / \
          a   t
We say that "rgeat" is a scrambled string of "great".
题意要求判断两个打乱的字符串是否是可以互相转化的。
转化规则是把字符串像二叉树分割,然后反转左右子树。
我们可以看出想要判断就得列出其中一个字符串的所有
分割反转的组合,检查是否有组合等于第二个字符串。
枚举组合解题一般都用DFS,判断过程中可以先检测两个
字符串的字符个数是否相等,可以提升速度。
6
string
很少考
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       I       R
And then read line by line: "PAHNAPLSIIGYIR"
看了好一会才理解题意,简单来说就是给你一个字符串和一个行数,要你把字符串用从上到下,在从下往上的放到每一行里面,然后最后水平输出新的字符。按照这个思路,我们创建一个n行数组,每一行是一个空字符,然后遍历字符,把字符放到相应行,同时更新行数到index从0到n从n到0,最后合并数组里面到字符。
161
string
Given two strings s and t, determine if they are both one edit distance apart.
Note:
There are 3 possiblities to satisify one edit distance apart:
  • Insert a character into s to get t

  • Delete a character from s to get t

  • Replace a character of s to get t

还以为是以前上课时候的那个dp题,这题只要你做一次改动,看两个字符串是否能相等。首先排除一些edge case,比如两个字符串长度相差超过1,两个字符串完全相等。
然后我们来遍历字符串s,当找到不一样字符的时候:
  • 如果s,t长度相等,就置换当前位置的字符

  • 如果s大于t的长度,就删除当前位置字符

  • 如果s小于t的长度,就添加当前位置字符

38
string
The count-and-say sequence is the sequence of integers with the first five terms as following:
1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
数数的题,题目初看很晕人,简单来说就是从头到尾数一个数字,连续的就计数,直到遇到不同值,把计数和数加入到结果字符串,然后继续数后面到数。
按照这个思路,我们需要不断的生成新的序列,用新的序列在生成下一个序列。

168
string
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB
    ...
Example 3:
Input: 701
Output: "ZY"
26进制的转换,把数除以26取余直到整数为0,余数作为转化的最右边的字母。
比如701除以26取余=25,
在加上A的unicode=65, 25+65-1=89转化为字母为Y
然后连接到结果字符串的左边。
171
string
Example:
Input:"AB"
Output: 28
Example :
Input:"ZY”
Output: 701
上一题的逆向解法,要把字符转化为26进制的数字。
从左到右遍历,把对应字母的值乘以位数加到最终结果。
倍数从0开始,每次多一位就把当前结果*26在加上新字母对应值
13
string
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
Input: "IV"
Output: 4
转换罗马数字到阿拉伯数字,首先要建一个数字的对应map
然后我们来看罗马数字的规律,从右到左看罗马数字,
我们比较当前位和前一位,如果当前值大于等于我们就累加,
小于就减。最后就能得到对应的数字。
12
string
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
数字转化乘罗马数字,要做这个要先建立罗马数字的对应字符,比如从1到9,10到90,100到900,1000到3000,题意说不会超过4000。然后我们把input分别除以1000,100,10,来寻找对应表中的罗马数子加到结果中便可。
273
string
Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”
数字转化成英语表达的题,和前面的题一样,需要建立1到19,20到90的对应英文表达表。然后写个递归:
从小到大检测,如果在0-19就从0-19的数组返回对应值。
如果小于100,就除以10去找10-90的十位数,然后把余数做递归
如果小于1000,就除以100找10-90的十位数在连接‘hundred’,然后把余数做递归
然后这样去找千,百万,十亿,把余数做递归





回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-2-19 15:48:17 | 只看该作者
全局:
第三天打卡, 主要做了string里面的sliding window 和 panlindrome 类型的题目。
# 名称 Tag& 频率 题目 解题
76 Minimum Window SubstringSubstring
Sliding Window
[color=rgba(0, 0, 0, 0.65)]Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
[color=rgba(0, 0, 0, 0.65)]Example:
Input: S = "ADOBECODEBANC", T = "ABC"Output: "BANC"

窗口类问题,这类问题解体思路和步骤一般如下:
1. 首先我们需要一个map来存t里面所有字符和其对应的出现次数,和一个count变量,
其值等于t的长度来记录还有多少个字母需要匹配,每匹配上一个count--,
当为0的时候说明我们找到一个窗口
2. 我们需要2个变量来追踪当前最小窗口的起始位置和长度
3. 遍历s,过程中我们检查当前字符在map中的次数,大于0则把他对应的count--,然后总count--。
当总count等于0,我们找到一个窗口,更新最小窗口起始位置和长度
4. 最后还要检测下当整个字符串为一个合法子串作为结果和整个字符串不合法返回空串的情况。

30 Substring with Concatenation of All Words SubstringSliding Window
[color=rgba(0, 0, 0, 0.65)]You are given a string, s, and a list of words, words, that are all of the same lengths.
Find all starting indices of substring(s) in s that is a concatenation of each word in
words exactly once and without any intervening characters.
Example 1:
Input:  s = "barfoothefoobarman",  words = ["foo","bar"]Output: [0,9]Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
这题有多种解法,我们还是来看窗口解法,
需要从s里面找到包含了words里面所有单词的窗口。
题目告诉我们单词的长度都一样,所以我们可以算出窗口的长度。然后一步步的移动窗口。
和上题一样,我们需要一个map来存当前word出现的次数,然后在每一个窗口,
我们需要一个个截取word长度的子串到map中判定是否在word中出现过。
这里,在每个窗口我们需要创建另外一个临时的map,
来记录这个窗口里words里面单词出现的次数,
最后当窗口比对完了之后我们只需要看两个map是否相等即可。
3 Longest Substring Without Repeating Characters SubstringSliding Window
Given a string, find the length of the[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]longest substring[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]without repeating characters.[color=rgba(0, 0, 0, 0.65)]
Example 1:
Input: "abcabcbb"Output: 3 Explanation: The answer is "abc", with the length of 3.

依然是窗口解法,这个不需要计数但是不能重复,还是要一个map来记录字母上一次出现的位置。
然后遍历过程我们维护一个窗口,我们把出现的字母的index加入/更新到map里面。
当遇到字母已经在map里面,说明遇到重复,需要跟新左边界:
我们就取该字符上一次出现位置+1和窗口左边界left两个中的大值。例子:
  • abba, 第二个b出现时候,b上一次位置+1比left大,窗口left为第二个b
  • abba,第二个a出现的时候,a上一次位置+1比left小,窗口left还是为left
最后一步我们在用窗口大小来跟新最大长度就好
125 Valid Palindrome Palindrometwo-pointer
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
[color=rgba(0, 0, 0, 0.65)]Note: For the purpose of this problem, we define empty string as valid palindrome.
[color=rgba(0, 0, 0, 0.65)]Example 1:
Input: "A man, a plan, a canal: Panama"Output: true
two pointer解法,由于只需要验证字母数字,所以遇到不是字母数字的直接跳过,
直到左右指针都是字母数字,我们就比较是否相等,
不等直接返回false,相等移动指针继续比较。
5 Longest Palindromic Substring Palindrome Given a string[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]s[color=rgba(0, 0, 0, 0.65)], find the longest palindromic substring in[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]s[color=rgba(0, 0, 0, 0.65)]. You may assume that the maximum length of[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]s[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]is 1000.
[color=rgba(0, 0, 0, 0.65)]Example 1:
Input: "babad"Output: "bab"Note: "aba" is also a valid answer.
遍历字符,从当前字符往两边扩展直到不相等或者到达边界,
然后跟新比较当前的palindromic substring到结果
9 Palindrome Number Palindrome Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
[color=rgba(0, 0, 0, 0.65)]Example 1:
Input: 121Output: true
这题其实不算字符串到题了,验证数字是否回文。
最容易想到到做法就是把数拆成一个个数字装进数组,然后在验证。
但是也可以不开数组做,做法就是找到数字最大divisor,比如1221,divisor就是1000,
然后我们可以用num / divisor找到第一位,num % 10找到最后一位来进行比较
214 Shortest Palindrome Palindrome Given a string[color=rgba(0, 0, 0, 0.65)] s[color=rgba(0, 0, 0, 0.65)], you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
[color=rgba(0, 0, 0, 0.65)]Example 1:
Input: "aacecaaa"Output: "aaacecaaa"
要求从字符串开头加字符,直到整个字符串成为palindrome。
思路很简单,把字符反转存到revt,然后从revt从0开始取子串,
直到子串等于s的开始子串。input: cacbb
revt = bbcac
当i=2,子串cac == input.startswith(cac), 然后截取revt0到i到子串加到s, 子串为bb
336 Palindrome Pairs Palindrome Given a list of[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]unique[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]words, find all pairs of[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]distinct[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]indices[color=rgba(0, 0, 0, 0.65)] (i, j)[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]in the given list, so that the concatenation of the two words, i.e.[color=rgba(0, 0, 0, 0.65)] words + words[j][color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]is a palindrome.
[color=rgba(0, 0, 0, 0.65)]Example 1:
[color=rgba(0, 0, 0, 0.65)]Input: ["abcd","dcba","lls","s","sssll"]Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
这道题的思路就是每个字符串,我们可以把它划分prefix和sufix,
比如例子里面到abcd,我们prefix可以划分[‘’, ‘a’, ‘ab’, ‘abc’, ‘abcd’], 对应sufix为[‘abcd’, ‘bdc’, ‘cd’, ‘d’, ‘’]。
当prefix为palindrome的时候,
我们只需要看对应sufix反转之后的字符是否在word list里面,
如果有,就找到一个pair。
这里prefix为’”’时候,sufix为’abcd’, 反转’dcba’,
然后我们在word list里面找到’dcba’, 把他们两个结果加入最终结果,然后继续搜索。记得也要查反转prefix能找到word的case
131 Palindrome Partitioning Palindrome Given a string[color=rgba(0, 0, 0, 0.65)] [i]s[color=rgba(0, 0, 0, 0.65)], partition[color=rgba(0, 0, 0, 0.65)] s[color=rgba(0, 0, 0, 0.65)] [color=rgba(0, 0, 0, 0.65)]such that every substring of the partition is a palindrome.
[color=rgba(0, 0, 0, 0.65)]Return all possible palindrome partitioning of s.
[color=rgba(0, 0, 0, 0.65)]Example:
Input: "aab"Output:[  ["aa","b"],  ["a","a","b"]]
要求找出所有划分字符串且所有子串都为回文串的方法,
直接用了DFS解决,枚举所以子串,检测是否为回文串,
是的话加入subset继续搜索。好像还有DP解法,下次解题再来做。





回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-2-20 15:42:54 | 只看该作者
全局:
第四天打卡,今天做了些二叉树的题,基本都是递归方面的。
#
名称
Tag& 频率
题目
解题
144
preorder
前序遍历,中左右
前几道热身题,递归很好写
94
Inorder
中序遍历,左中右
还是写了下迭代的方法
145
postorder
后序遍历,左右中
postorder迭代需要mark一下node是否visited,visited为True
表示没有右节点或者从右节点返回,可以加入result
102
DFS + BFS
Given a binary tree, return the level order traversal of its nodes' values.
(ie, from left to right, level by level).
For example:  Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

return  [[3], [9,20],  [15,7]]


这题可以用DFS或 BFS做, DFS的话用一个depth标示level。





Preorder




100
preorder

检测两个tree是否一样,结构和值都一样。写个递归检测,主要注意一些case,当2个节点为空返回true,当两个中只有一个有节点(结构不一样),返回false。最后在检测值相等,递归左右节点。
101
preorder
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
    1
   / \
  2   2
/ \ / \
3  4 4  3
和上一题当思路一样,只是我们把root当左右子节点当成2个新当tree,然后递归验证,唯一不一样当地方就是递归当时候我们传递的节点要调换一下: (p.left, q.right),  (p.right, q.left)
226
preorder + BFS
nput:                                  Output:
     4                                         4
   /   \                                    /   \
  2     7                                 7     2
/ \   / \                            / \   / \
1   3 6   9                         9   6 3   1
反转左右子数,递归的时候调换左右子树即可
257
preorder
Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example:
Input:
   1
/   \
2     3
\
  5
Output: ["1->2->5", "1->3"]
用一个path变量记录递归的值,当到达叶子节点的时候就把path加到result里面。
112
preorder
Example:
Given the below binary tree and sum = 22,
      5
     / \
    4   8
   /   / \
  11  13  4
/  \      \
7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
递归的时候把sum的值减去当前node的值,到达叶子节点的时候检测一下是否为0即可。
113
preorder

path sum的follow up, 不仅要求找出path,还要把所有path记录下来。同样的思路,只是在递归的时候需要维护一个subset来存当时的path上的nodes,找到一个之后就把subset放进result。
129
preorder
Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
path sum的变形题,只是这次要求每个path的数组成的数字加起来的和。同样的递归,需要维护一个当前节点组成的数字num。


评分

参与人数 1大米 +3 收起 理由
14417335 + 3 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-2-27 15:52:33 | 只看该作者
全局:
最近两个项目缠身,好几天抽不开身来,第5天打卡,二叉树的一些题目。
# 名称 Tag& 频率 题目 解题
298 Binary Tree Longest Consecutive Sequence binary tree Given a binary tree, find the length of the longest consecutive sequence path.The path refers to any sequence of nodes from some starting node to any node
in the tree along the parent-child connections.
The longest consecutive path need to be from parent to child (cannot be the reverse).
要求寻找二叉树中连续的序列,序列只能从上到下连接。所以我们只能从上到下递归的时候来找出序列。
递归的时候需要一个变量来记录当前最长序列,
一个变量传递当前节点的值到下一层判断是否连续。
111 Minimum Depth of Binary Tree binary tree Example:Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.
用递归自底向上来做,从叶子节点开始计数,每上一层返回左右子树较小值+1。
104 Maximum Depth of Binary Treebinary tree Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its depth = 3.
和上面minimum depth一样,只是返回的时候返回较大的
110 Balanced Binary Tree binary tree a binary tree in which the depth of the two subtrees of every node never differ by more than 1.Example 1:
Given the following tree [3,9,20,null,null,15,7]:
    3
   / \
  9  20
    /  \
   15   7
Return true.
要判断树是否为平衡树,任何子树高度差不超过1。解题思路和上面差不多,我们还是需要自底向上的
记录当前左右子树的高度,但是要多加一个判断:
判断当前左右子树的高度差,大于1的话就返回-1。
不大于返回当前最大的高度
124 Binary Tree Maximum Path Sum binary treeGiven a non-empty binary tree, find the maximum path sum.For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
       1
      / \
     2   3
Output: 6
题意让我们找出二叉树中任意一点到另一点的path sum。我们先来看要找出当前节点的path sum,如果是叶子节点,
就只返回当前节点,还要更新下maxSum,因为一个节点也算。
然后非叶子节点我们看有左右子树的情况,我们首先需要把当前节点+左节点
返回值(如果是正数)+右节点返回值(如果是正数),这就是当前节点能构成的最大path sum,然后跟新下maxSum。
现在我们已经找到来所有path sum的情况了,但是我们还要处理下返回的时候的值。因为上一层的节点只需要你提供一个最大path,所以要从左右子树中选出大的来加上自己返回
250 Count Univalue Subtrees binary treeGiven a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
题目意思是找出所有子树符合:子树的所有节点值一样。
题目要求找出多少个,我们需要递归的时候发现一个就加入到counter里面。
递归的过程需要判断:
1 左右子树是否是unitree
2. 如果是,那么当前节点是否和左右孩子值一样,不是返回false
3.如果是,当前节点subtree为unitree,加入counter返回true
366 Find Leaves of Binary Tree binary tree Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
[color=rgba(0, 0, 0, 0.65)]Example:
Input: [1,2,3,4,5]            1         / \        2   3       / \           4   5    Output: [[4,5,3],[2],[1]]
直接用了一个map来保持没一层的元素,采用自底向上,叶子节点算第1层,
当前节点的层数为左右子树较大层数+1。比如例子
中的1,左子树返回层数2,右子树返回层数1,我们
取2+1为3,作为1的层数,放进相应数组。
337 House Robber III binary treeThe thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root."
Besides the root, each house has one and only one parent house.
After a tour, the smart thief realized that "all houses in this place forms a binary tree".
It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
抢还是不抢,典型的DP。思路就自底向上,我们每一步都要选择抢或者不抢,抢,那我们就要当前值加上之前一层不抢都收益。不抢,我们就加上上一层抢都收益。
所以我们每一层需要计算抢和不抢都收益返回就好。
最后在root取两者大都一个。

回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-2-28 15:49:47 | 只看该作者
全局:
第六天打卡,二叉树和二叉查找树的题目
107
BinaryTree
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

和第一题差不多,调换下顺序就好了。
任然用可以用BFS, DFS来做,简单的练习。
103
BinaryTree
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return:  [ [3],
  [20,9],
  [15,7]]
level order的变形题,解法大体类似。
要求打印出二叉树中按之字形走的值。
不难看出奇数行从左到右,偶数行从右到左。
所以我们只需要在递归的时候记录下当前的level
看看是奇数还是偶数,我们就可以知道该往相应
数组的前面加入还是后面加入了。
199
BFS postorder
BinaryTree
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
求从右边看过来能看到的数字的集合,postorder遍历
就能保证当前行最右边的数最先被加入结果中。








98
BST
preorder
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
  • The left subtree of a node contains only nodes with keys less than the node's key.

  • The right subtree of a node contains only nodes with keys greater than the node's key.

  • Both the left and right subtrees must also be binary search trees.

验证二叉查找树,根据二叉查找树的性质来验证。
可以看出我们在递归的时候需要判定当前值是否在
当前的左右边界范围内就行了,需要注意的是
更新边界的时候,比如递归到左子节点,
我们需要更新右边界,
右边界值为当前右边界和当前节点值的较小值
235
BST
preorder
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
给定两个二叉查找树的节点,要求找他们的
最低公共先祖节点。递归分三步
1.递归遇到空或match就返回当前节点,
2.递归左右子节点
3. 左右子树返回值,如果都不为空说明
左右子节点为p, q返回当前节点
4.接下来就是只有左节点或右节点的情况了,
返回不为空的一边
236
BST
postorder
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
和上题解法一样
108
BST
binary search
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
不难看出排序的数组在结合二叉查找树性质,
二分查找就可以确定所有数的位置。
109
BST
binary search
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
把数组换成了linkedlist, 然后找linkedlist的中间
位置的方法就是快慢指针。
173
BST
inorder
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
一道设计iterator的题

回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-3-1 15:08:15 | 只看该作者
全局:
第7天打卡,继续BST
# 名称 Tag& 频率 题目 解题
230 Kth Smallest Element in a BSTBSTinorder
Input: root = [3,1,4,null,2], k = 1   3
  / \
1   4
  \
   2
Output: 1
和写bst iterator思路差不多,用迭代或递归方法来中序遍历,就是bst中从小到大的顺序, 然后数到k就是结果
297 Serialize and Deserialize Binary TreeBSTBFS
Design an algorithm to serialize and deserialize a binary tree. 要求序列化一个二叉树,我的解法是将用中序遍历将二叉树值序列化成一个字符串,空节点用‘$’代替。
反序列化的时候,将字符split一一取出,
遇到$直接返回,不然开始组装节点,然后在
中序遍历组装其左右子节点。
285 Inorder Successor in BST BSTinorder
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.The successor of a node p is the node with the smallest key greater than p.val.
给定一个节点,要求该节点中序遍历顺序下的的下一个节点1.当节点没有右孩子,中序遍历就是他的父节点
2 当节点有右孩子,中序遍历为右孩子的最小左孩子
因为是bst所有可以用当前node值来和p比较
小于往左,大于或等于往右;
递归过程中我们用一个变量保存当前successor
小于时候就把当前node赋予successor
270 Closest Binary Search Tree Value BSTpreorder
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 给定一个浮点数,要求在BST中找出最近的数,根据BST的性质,我们只需要判断当前节点与
浮点数大小,就能决定往那方向走,总共时间为o(h).
每到一个节点就计算当前节点与浮点数绝对差值,
然后比较更新到结果
272 Closest Binary Search Tree Value II BSTinorde
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target. follow up,增加了一个条件就是从找一个变成了找k个。这样的话我们就需要比较predecessors和successors,
每次从中选出最接近的加入结果。
现在我们用一个dq来存predecessors和successors,
中序遍历把节点放入dq,然后我们每次从dq两端拿出
节点比较,把较大的移除出去,最后剩下k个最接近的
99 Recover Binary Search Tree BSTinorde
Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.
BST的两个变量被置换了,要求换回来。暴力解法就直接开空间置换空间复杂度O(N).
不开空间的话就用inorder traverse,我们只需要用一个
变量记录其presuccessor,如果当前值小于presuccessor
将其放入需要置换队列,最后我们在置换两个元素值即可
156 Binary Tree Upside Down BinaryTree低频
Given a binary tree where all the right nodes are either leaf nodes with a sibling
(a left node that shares the same parent node) or empty,
flip it upside down and turn it into a tree where
the original right nodes turned into left leaf nodes. Return the new root.


用了图中解法,首先找到leftmost节点,然后
把所有有右节点的copy到predecessor的左节点。
然后把当前节点作为predecessor的右节点
114 Flatten Binary Tree to Linked List BinaryTree中低频
Given a binary tree, flatten it to a linked list in-place. 记得以前用stack做的,看了下别人思路有个非常简洁的解题方法。首先需要一个变量track上一个节点pre,
然后用右左中的顺序递归,(preorder是中左右的顺序)
然后在当前节点把右节点设置成pre,再把左节点清空,
最后把当前节点赋值给pre
比如, 首先会到达3,把3设为pre,然后会到达2,
会把2的右节点设置为pre,现在2是pre
最后会达到1,会把2设置成右节点,然后清空左节点。
   1                1                   1
  /\              /                      \
2    3          2                          2
                   \                             \
                     3                             3


回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-3-3 15:52:27 | 只看该作者
全局:
第八天打卡
# 名称 Tag& 频率 题目 解题
255 Verify Preorder Sequence in Binary Search Tree BST低频
Given an array of numbers,
verify whether it is the correct preorder traversal sequence of a binary search tree.Input: [5,2,6,1,3]
Output: false
用一个stack,遍历过程中不断把值压栈,
如果当前值大于了stack中最后一位,说明到了
右子树,就把stack里面所有小于当前值pop出来,
期间还要用一个变量不断跟新pop出来的lower bound,
之后要是有值比lower bound大就返回false
105 Construct Binary Tree from Preorder and Inorder Traversal BinaryTree
中低频
example,            5
           / \
          3   2
         / \   \
        1   4   6
the preorder and inorder arrays are:
preorder: 5 3 1 4 2 6
inorder: 1 3 4 5 2 6
给定前序中序遍历的数值,要求重新组建二叉树,根据例子我们可以看出
preorder: 5 (3 1 4) (2 6)
inorder: (1 3 4) 5 (2 6)
由于中序遍历总会比前序遍历先遍历左子树,
所以当前节点的中序遍历的位置的左边就是左子树,
右边为右子树。
然后把左子树单独拿出来:
preorder: 3 1 4
inorder: 1 3 4
右子树为:
preorder: 3 6
inorder: 3 6
如此这般便可把整个数给重组起来
106 Construct Binary Tree from Inorder and Postorder Traversal BinaryTree
低频
Given inorder and postorder traversal of a tree, construct the binary tree. 和上题类似,换了postorder,观察不难发现,只要这题只要从右到左的拿出元素就能用上面思路组建二叉树。
116 Populating Next Right Pointers in Each Node BinaryTree高频
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
https://assets.leetcode.com/uploads/2019/02/14/116_sample.png
需要把同一层的所有节点用一个next连接其同一层相邻的右边节点。我们需要连接当前节点左右孩子和处在同一层的节点。
递归的时候我们只需要做2件事:
  • 如果有左右孩子,把他们连起来
  • 如果当前节点有next,并且有左右孩子,
我们需要连接当前节点右孩子的next到
当前节点next的左孩子处,这样就把跨子树的同一层节点连起来了
117 Populating Next Right Pointers in Each Node II BinaryTree中高频
Given a binary treestruct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
上一题follow up。现在tree不是满二叉树,中间可能有空节点。思路就像是bfs,我们一层层的去把node串起来。
这里首先我们建立一个类似linked list的head和tail,然后把
当前node的左右节点(如果存在)串起来,tail永远指向最后一个
节点。当前节点串完之后如果node有next,我们就移动node,
继续串剩下的节点。
当一层串完了,就是node没有next节点,我们就把head.next
用来替换node,开始更新下一层。
314 Binary Tree Vertical Order Traversal BinaryTree中高频
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).If two nodes are in the same row and column, the order should be from left to right
要求把所有二叉树的值按列归类。往左就是-1,往右就是+1.当值为同一列的时候就加入集合。这题得开一个map,来存
列→同一列的集合。最后把map里面数组拿出组合。
遍历过程我用了BFS, 一层层的扫。
96 Unique Binary Search Trees BinaryTree中低频
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 给定一个n,问我们用1到n的数可以建立多少个唯一的BST。DP解法,公式为F(i, n) = G(i-1) * G(n-i)   1 <= i <= n
F(i, n)为用数字i作为root,从n个数里能建立BST的个数。
F(1, 3) = G(1-1) * G(3-1)为用1作为root,用123能组成BST个数。

回复

使用道具 举报

🔗
 楼主| creazy-lobster 2019-3-4 14:55:45 | 只看该作者
全局:
第九天打卡, Math 类题目
# 名称 Tag& 频率 题目 解题
7Reverse Integer Math
高频
Given a 32-bit signed integer, reverse digits of an integer.Example 1:
Input: 123
Output: 321
直接转字符reverse是最暴力简单的。用数学方法就是除10取余取最后一位,然后原数除10消掉最后一位。然后把每次取到的数加到新数上
165 Compare Version Numbers Math
中频
Example 2:Input: version1 = "1.0.1", version2 = "1"
Output: 1
Example 4:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1”
这题就考简单的字符操作,各种testcase的考虑
66 Plus One Math
高频
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
给一个数组代表一个数字,我们要完成加1后整个数的更新。从右往左,我们需要用一个carry变量记录当前是否有进位,
有的话加上。然后在判断这一位是否能进位,能的话carry
= 1,不能carry = 0。最后循环完了之后还需要判断一次
carry是否是否为1,如果是的话我们需要在数组前面加
上1
258 Add Digits Math低频
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
             Since 2 has only one digit, return it.
这题如果知道公式直接套公式解O(1)
  • dr(n) = 1 + (n - 1) % 9
但是如果不知道,也可以用前面的方法,把数字一个个拆出来加起来
67 Add Binary Math高频
Given two binary strings, return their sum (also a binary string).The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
算二进制加法,就是计算的时候注意一些cornor case
43 Multiply Strings Math
高频
Input: num1 = "2", num2 = "3"Output: "6”
算字符串乘法,不让转换成整数。主要要你模拟乘法过程,用一个数组来记录乘积,一图胜千言




69 Sqrt(x) Math
高频
Implement int sqrt(int x).Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
要求开平方,二分法来做,首先我们要定义lowerbound,higherbound分别为0,x。然后我们将他们的和除以2的值用来当中间点,以8为例子,l =0, h = 8, mid = (0+8)//2 = 4
然后我们平方中间数,为16,大于我们的x,我们就移动higherbound = mid -1 = 3。
接下来继续找,mid = (0+3) // 2 = 1, 1的平方小于8,移动 lowerbound到mid+1,2。
接下来,我们只有2和3两个candidate了,2的平方4,3的平方9,所以2为最下的开方整数。
50 Pow(x, n) Math
高频
Implement pow(x,n), which calculates x raised to the power n (xn).Example 1:
Input: 2.00000, 10
Output: 1024.00000
实现pow方法,虽然已经有buildin了,还是来实现一下。写个递归每次乘1次x就可以。但是要考虑负n情况,就要返回1/pow(x,-n)
还要考虑n为奇数和偶数情况,偶数用pow(x,n/2), 奇数还需要在乘上一次
367 Valid Perfect Square Math
低频
Given a positive integer num, write a function which returns True if num is a perfect square else False.Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
要求检测给定的数是否能被开方成整数。用之前我们69题的二分法,同样的套路,不断缩小搜索范围,找到就返回true,
到最后2位数的时候如果都没有match就返回false
365 Water and Jug Problem Math Input: x = 3, y = 5, z = 4Output: True
经典的brainstorm题目,给你两水杯size分别x, y。让你判断是否能最终有一个或两个杯子都有z升水。
这个题的数学方法就是算出x和y的最大公约数,看最大公约数是否是z的倍数,是的话就可行。





回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表