AlgorithmPractice
杭电OJ100道
2024 c语言合法标识符
There are two ways to accept all chars including space
- use char array, but you need to set the MaxLength for limit the length of buffer
- use string, it’s more convenient.
and there are two diff ways to get the length of str
- using < cstring > like: remember to
#include <cstring>
then usestrlen(str)
to get the length you wanted.- if you use string, then you can just use the function
length()
like:str.length()
, it will return the length of the string.
1 | //use char array |
Use cctype to judge whether a char is num or alpha
there are three useful fun:
- isalpha() //check if the char is alpha , both upper and lower
- isdigit()
- isalnum() //check if the char is alpha , both upper and lower or num
1 | bool isValidIdentifier(string s){ |
Or, you can use you own way to judge it.
1 | int f=1; |
1 |
|
2026 将每个单词首字符变成大写
Use sstream
there are some examples to use sstream
Converting a string to other types of data
- We define a string variable
str
to receive data from input.- Then we create a stringstream object
ss
, and pass the str into the object.- Finally, we use the
>>
operator of thess
object to convert the data in the string to the specified data type and store it in the corresponding variable.
1 |
|
Converting other types of data to a string
- we first define three variables
num
,dbl
, andflag
, which are assigned integer, double-precision floating-point, and boolean data, respectively.- We then create a stringstream object
ss
and use the<<
operator of thess
object to convert these data to a string and store it in thess
object.- Finally, we use the
str()
function of thess
object to convert the data inss
to a string and store it in the variablestr
, which is then outputted.
1 |
|
Here is the problems’ resolution
- We define a string variable
str
to receive data from input, then create a stringstream objectss
and passstr
into it.- We split
ss
into words by space- Convert the first letter into upper and prinf out the result.
1 |
|
However , if we forget to use toupper, then we can converse the letter into upper one by one, like this.
1 | if (str[i] >= 'a' && str[i] <= 'z') { |
Here is another resolution that we find a letter which is next to a space, then convert it into upper
1 | (isalpha(t[i]) && t[i-1] == ' ') ? toupper(t[i]) : t[i]); |
toupper
1 |
|
tolower
1 |
|
isupper
1 |
|
isalpha
To judge if a character is a alpha
1 |
|
isdigit
To judge if a character is a digit
1 |
|
isalnum
To judge whether a character is a letter or a digit
1 |
|
isspace
To judge if a character is space
1 |
|
2027 统计元音
count vowels
As usual,
- first we define a char array named
vowels
as {a,e,i,o,u}, and create a int array namedarr
to record results.- we define a string valiable
sentence
to receive data from input- use
switch
to judge every character in the sentence, remember to usetolower
to get a lower char
1 |
|
2028 *最小公倍数
Lowest Common Multiple
Before we solve this problem, we need to learn some new things
- Greatest Common Divisor(最大公约数) 【GCD】
- Lowest Common Multiple(最小公倍数) 【LCM】
You can use the GCD (Greatest Common Divisor) to find the LCM (Lowest Common Multiple) of two numbers using the following formula:
- LCM(a, b) = (a * b) / GCD(a, b)
So, we need to find GCD before we find LCM, here is an example to get gcd.
Find the GCD of 12 and 18:
- Divide the larger number by the smaller number and find the remainder.
18 / 12 = 1 remainder 6
- Divide the smaller number by the remainder and find the new remainder.
12 / 6 = 2 remainder 0
- The GCD is the
remainder
of the last division, which is6
.
Here are codes to get GCD, and there are two approaches.
- recursion
1 | int gcd(int a, int b) { |
- iteration
1 | int gcd(int a,int b){ |
Here is the complete code
1 |
|
2029 回文串判断
Judge whether a string is a palidrome
Here’s a trick , if the string is a palidrom, then the loop won’t break , then
i
will equals tolen/2
asi==len/2
1 |
|
2031 *R进制转换
input a decimal number and convert it into an R-ary number
To convert a decimal number into an R-ary number, you need to follow these steps:
- Divide the decimal number by the
radix (R)
and note down theremainder
.- Divide the
quotient
obtained in step 1 by R and note down theremainder
.- Repeat step 2 until the
quotient
becomes zero.- The
remainders
obtained in step 1, 2, and 3, when read inreverse
order, form the R-ary representation of the decimal number.
Let’s take an example to understand this process. Suppose we want to convert the decimal number 37 into a binary number (R = 2).
- Divide 37 by 2. The quotient is 18 and the remainder is
1
. Note down the remainder.- Divide 18 by 2. The quotient is 9 and the remainder is
0
. Note down the remainder.- Divide 9 by 2. The quotient is 4 and the remainder is
1
. Note down the remainder.- Divide 4 by 2. The quotient is 2 and the remainder is
0
. Note down the remainder.- Divide 2 by 2. The quotient is 1 and the remainder is
0
. Note down the remainder.- Divide 1 by 2. The quotient is 0 and the remainder is
1
. Note down the remainder.
Reading the remainders in reverse order, we get 100101, which is the binary representation of the decimal number 37.
convert the decimal number 37 into a hexadecimal (R=16) number.
To convert 37 into a hexadecimal number, we can follow the same process as explained earlier, but this time we will divide the decimal number by 16 instead of 2.
Here are the steps:
- Divide 37 by 16. The quotient is 2 and the remainder is
5
. Note down the remainder.- Divide 2 by 16. The quotient is 0 and the remainder is
2
. Note down the remainder.
Reading the remainders in reverse order, we get 25, which is the hexadecimal representation of the decimal number 37.
1 |
|
2032 杨辉三角
YangHuiTriangle
The rules as following
f(i, i) = f(i, 1) = 1 (i > 0)
f(i, j) = f(i-1, j) + f(i-1, j-1) (j < i)
1 |
|
2034 集合问题A-B
Find the elemetns in A but not in B, both A and B is a ascent set.
We can use “two pointers” to solve this problem, here is the details
- We define an int array to receive numbers from input
- Define curA initialized as 0 as the begining of set A and curB initialized as 0 as the begining of set B, they are two pointers start from different index
- if
arr[curA]==arr[curB]
, it means both set A and set B has this number- if
arr[curA]>arr[curB]
, not sure whether B has the same number, so just skip arr[curB]- if
arr[curA]<arr[curB]
,it means the arr[curA] is only in set A but not in set B- if setA has some numbers left, we just output them directly
1 |
|
two pointers
PorblemA
Given a set named arr of positive decimal numbers that is sorted in ascending order and a positive integer M, the task is to find every pair of numbers in the set whose sum equals M
Here is the solution
- Define two pointers
i
andj
, wherei
initialized as0
andj
initialized aslen-1
, len is the length of the set.- i will shift to len-1, and j will shift to 0 until
i>=j
- if
arr [i]+arr [j]==M
, it means that we find one of the answer ,then justoutput
it.- if
arr [i]+arr [j]>M
, it means that we need to decrease the sum of left part, the real answer will show in [i,j-1],- if
arr [i]+arr [j]<M
, it means that we need to increase the sum of left part, the real answer will show in [i+1,j]
1 | //remember that the array is sorted in ascending order. |
Merge
Given two sets which are sorted by ascdenting order, the task it to merge them into a new set which needs to be in ascdenting order and print out the result.
We can also use the two pointer to solve this problem.
- We create two arraies named arrA adn arrB to receive numbers from input, lenA and lenB are the length of array ,respectively.
- Define two pointer i and j ,both of them are initialized as 0
- While
i<lenA
andj<lenB
, we need to judge these cases- if
arrA[i]<arr[B]
,it means we need to push arrA[i] into the new array, andi++
- if
arrA[i]>=arr[B]
,it means we need to push arrB[j] into the new array, andj++
- then remember to push the left number into the new array if arrA or arrB has some numbers left
1 |
|
2035 集合问题A^B
Find the integer represented by the last three digits of A^B.
Explanation: A^B means “A to the power of B”
Here is a more powful fomula
1 | 1 n = 0 |
1 |
|
2036 计算多边形面积
Calculate the area of polygon
The formula as following
S = 0.5 * ( (x0y1-x1y0) + (x1y2-x2y1) + …+ (xn-1yn-xnyn-1) + (xny0-x0yn) )
1 |
|
2037 *贪心算法|独立区间
indenpendent intervals
If you have 24 hours to watch different TV shows , and ther are many shows which can be seen as a interval, it is best to start with the latest one to ensure that it is the last show you watch.If there are two shows that start at the same time, you should definitely pick the shorter one in order to watch as many shows as possible.
So, here’s the rule to reorder these shows.
- Sort the intervals(shows) in descending order by their start time.【To ensure that it is the last show you watch】
- If two intervals have the same start time, sort them in ascending order by their end time.【To pick the shorter one】
1 |
|
2040 亲和数
Two numbers are affine if either of them is the sum of the proper divisors of the other.
1 |
|
2041 *斐波那契
There is a staircase with M levels. At the beginning, you are on the first level. If you can only step up one or two levels at a time, how many ways are there to get to the Mth level?
To reach second level,you can take one stop from first level.
To reach third level, you can take two steps directly from first level or you can take one step from second level.
To reach nth level , you can take one step from n-1th level or you can take two steps from n-2th level.
1 |
|
2043 判断是否为强密码
Rules.
- The length of password should be longer than or equals to 8 but not more than 16.
- The characters should come from at least three of the following “character categories”
category
- Uppercase letters A.B.C~z
- Lowercase letters a.b.c~z
- Numbers 0.1.2~9
- Special characters. ~,!,@,#,$,%,^;
1 |
|
2044 斐波那契2
There is a trained bee that can only crawl to the adjacent hive on the right, and cannot crawl in the opposite direction. Please program to calculate the number of possible routes for bees to climb from hive a to hive b.
Among them, the structure of the hive is as follows.
To reach hive n, you can crawl from hive n-1 or hive n-2, it’s the same one like 2041.
For example, to reach hive 5 , you can crawl from hive 3 or hive 4
1 |
|
2045 RPG问题|斐波那契3
There are n squares arranged in a row, and each square can be painted with one of three colors: Red, Pink, or Green. Any two adjacent squares cannot have the same color, and the first and last squares cannot have the same color. Find the total number of ways to color all the squares under these constraints.
- one square:3
- two squares: C(3,1)*C(2,1)=6
- three squares: C(3,1)*C(2,1)*C(1,1)=6
- four squares: there are two different situations
- We set F(4) initiaized as 0,
F(4)=0
- If the first square is same as the third square :negative_squared_cross_mark::black_large_square::negative_squared_cross_mark:,then there are
two color
for the forth square.
- :negative_squared_cross_mark::black_large_square::negative_squared_cross_mark::black_large_square:or :negative_squared_cross_mark::black_large_square::negative_squared_cross_mark::white_large_square:
- F(4)+=F(2)*2 【Because the third square must be same as the first one, it can’t chose other color】
- If the first square is different from the third square :negative_squared_cross_mark::black_large_square::white_large_square:, then
only one color
for the forth square cuz two adjacent squares cannot have the same color and the first and last squares cannot have the same color
- :negative_squared_cross_mark::black_large_square::white_large_square::black_large_square:
- F(4)+=F(3)*1
F(4)=F(3)*1 + F(2)*2
- N squares:
F(n)=F(n-1)+F(n-2)*2
;
1 |
|
2046 骨牌铺方格|斐波那契4
In a 2×n rectangular grid, where n is an integer, find the total number of ways to completely cover the grid using 1×2 dominoes.
To cover Nth dominos over the grid, we can add
one vertical dominoe
at the end of the arrangement of(N-1)th
dominos.Or we can also add
two horizonal dominos
at the end of the arrangement of(N-2)th
, We can’t add a vertical one otherwise it will be the same as the first case.So F(n)=F(n-1)+F(n-2)
1 |
|
2047 字符串EOF的排列组合|斐波那契5
The task is to generate a string of length n consisting of only three characters “E”, “O”, and “F” (which may have only one or two of these characters, but cannot have any other characters). It is forbidden to have adjacent “O” characters in the string.
- We define a two-dimentional array dp
- dp[n][1] represents the string ending with “E” or "F"
- dp[n][0] represents the string ending with "O"
- If the former legal string ending with “E” or “F” or “O”, then we can
add "E" or "F"
- dp[n][1]=2*(dp[n-1][1]+dp[n-1][0])
- If the former legal string ending with “E” or “F” but not “O”, then we can
add "O"
- dp[n][0]=dp[n][1]
We initialize the
dp[0][0]
as 1 which represents “O”and initialize
dp[0][1]
as 2 which represents “E” or “F”
1 |
|
2048 *错排问题1
All permutations of N tickets may naturally be Ann = N! permutations
The problem now is that there are several ways to arrange N tickets wrongly.
- let’s consider that if none of the previous N-1 people took their own tickets, that is, the previous N-1 people met the wrong order, and now another person comes, and he has his own ticket in his hand.
As long as he exchanges his ticket with any one of the other N-1 people, he can satisfy the wrong arrangement of N people. At this time, there areN-1
ways.
- F(n)+=(n-1)*F(n-1)
- In addition, we can consider the case where the first N-1 people do not satisfy the derangement, but the Nth person exchanges their ticket with one of the previous people and exactly satisfies the derangement.This situation occurs when among the original N-1 people, N-2 people satisfy the derangement and only one person holds their own ticket, and the Nth person happens to exchange with that person, which satisfies the derangement. Because in the first N-1 people, each person has a chance to hold their own ticket. Therefore, there are N-1 possibilities for the exchange.Because among the top N-1 people, everyone has a chance to hold their own ticket. So there are
N-1
possible exchanges.
- F(n)+=(n-1)*F(n-2)
- Even though the formula is F(N)=(n-1)*(F(n-2)+F(n-1)), but the (n-1)'s meaning is different
1 |
|
2049 错排问题2
Here is the explanation of the derangement problem for selecting M people from N people.
To solve the derangement problem for selecting M people from N people, we can use a similar approach as the regular derangement problem.
Firstly, the number of ways to select M people from N people is given by the formula C(N,M) = N! / (M! * (N-M)!), which is a known quantity.
Next, we consider the derangement problem for these M people, where each person is not in their original position.
Let D(M) be the number of derangements for M people, then we can use the following recurrence relation:
D(M) = (M-1) * [D(M-1) + D(M-2)]
Here, D(M-1) represents the number of derangements for M-1 people, where the Mth person cannot be in the Mth position, and D(M-2) represents the number of derangements for M-2 people, where the Mth person cannot be in the (M-1)th position. Since the Mth person cannot be in the Mth position, there are M-1 choices.
The initial conditions are D(1) = 0 and D(2) = 1, since there is no derangement problem with one person, and there is only one derangement with two people.
Finally, the number of derangements for selecting M people from N people is given by
C(N,M) * D(M)
.
1 |
|
2050 拆线分割平面
Before we start to solve this problem, let’s see another problem
How many pieces will get at most divided by N intersecting straight lines
When adding the n-th straight line, it can intersect with the previous n-1 straight lines at most, because if it is parallel to the n-1th straight line, it will not create new regions. Therefore, the n-th straight line can create at most n-1 new intersection points.
Meanwhile, the nth straight line divides the plane into n+1 regions. Thus, the total number of regions is the sum of the total intersection points created by the first n-1 straight lines and the new regions created by the n-th straight line.
Specifically:
- The total number of intersection points created by the first n-1 straight lines =
- 1 + 2 + 3 + … + (n-1) = n*(n-1)/2
- The new regions created by the n-th straight line = n+1
Therefore, the total number of regions is:
(n*(n-1)/2) + (n+1) = (n^2 + n + 2)/2
So, when adding the n-th straight line, the maximum number of regions that the plane can be divided into is
(n^2 + n + 2)/2.
2053 开关灯
There are many lamps in a line. All of them are off at first. A series of operations are carried out on these lamps. On the i-th operation, the lamps whose numbers are the multiple of i change the condition ( on to off and off to on ).
Each test case contains only a number n ( 0< n<= 10^5) in a line.
Output the condition of the n-th lamp after infinity operations ( 0 - off, 1 - on ).
Take n=16 for an examples, because it’s approximations are 1,2,4,8,16 so the 16th light will be adjusted on the 1st, 2nd, 4th, 8th and 16th operations.There are a total of 5 operations and since it starts as off status, it will end up being on.
The final status of the light depends on it’s parity of the number of approximations , if the number of divisors of n is odd, then output 1 , otherwise output 0;
1 |
|
To think further, if we consider n=B*A, we can observe that the number of divisors of n will be even if all the
B
not equals toA
, it means the light end up being off.On other hand, only the number of divisors is odd can turn on the light! Therefore, we only need to check whether the input number is a perfect square number
1 | /** |
2054 A=B_Plus
Give you two numbers A and B, if A is equal to B, you should print “YES”, or print “NO”.
Notice that the number is not decimal or double variable, it could be a string variable or a long char type.
So we should deal with it a bit before we compare them
- Remote redundant zeros befrore the real effctive number, like 00001.2=1.2
- Remote redundant zeros at the end of the string, like 1.0010000=1.001
1 |
|
string.find()
In C++, the string class provides the find function to find the position of a substring in the original string. The find function has multiple overloaded versions, among which the commonly used versions are as follows:
1 | copy codesize_t find(const string& str, size_t pos = 0) const; // Find the first occurrence of the string 'str' in the original string, starting the search from position 'pos |
The return value of all four versions above is of type size_t, which indicates the starting position of the found substring in the original string (if not found, it returns string::npos, which is -1).
2055 AEasyProblem
1 |
|
2056 计算重合部分的矩阵面积
Calculate the area of the intersection of two rectangles.
We consider the intersection is a rectangle (sure it is).Therefore, we require the coordinates of two points on the diagonals of the rectangle.
Then we get the formula as following.
X=max(x1,x3)=max(2,3)=3
Y=max(y1,y3)=max(1,2)=2
X’=min(x2,x4)=min(5,5)=5
Y’=min(y2,y4)=min(5,7)=5
(X,Y)=(3,2) (X’,Y’)=(5,5)
1 |
|
2058 *找到连续子段和为M
Given a sequence 1,2,3,…N, the task is to calculate all the possible sub-sequences that the sum of the sub-sequence is M
- Define two pointers as
start
andend
,initiazlied as 0 and 1 respectively, and define an array range from 1 to n;- We create a decimal variable sum initialized as dp[0];
- While
end
lower thann
, excute the loop until end equals to n;- if sum<m, then
sum+=dp[end]
, and move end to next num ,end++
- if sum=m, output the result and remember to move end to the next num to search next sub-sequence ,
sum+=dp[end]
- if sum>m,
sum-=dp[start]
, meve start to next num ,start++
For example, Let’s consider N=20, M=10. dp[20] from 1 to 20, sum=1, start=0, end=1;
20 10
sum<M: excute: sum+2 end 1
sum 3 start 0 end 2
sum<M: excute: sum+3 end 2
sum 6 start 0 end 3
sum<M: excute: sum+4 end 3
sum 10 start 0 end 4
[1,4]
sum=M: sum 15 start 0 end 5
sum>M: excute: sum-1
sum 14 start 1 end 5
sum>M: excute: sum-2
sum 12 start 2 end 5
sum>M: excute: sum-3
sum 9 start 3 end 5
sum<M: excute: sum+6 end 5
sum 15 start 3 end 6
sum>M: excute: sum-4
sum 11 start 4 end 6
sum>M: excute: sum-5
sum 6 start 5 end 6
sum<M: excute: sum+7 end 6
sum 13 start 5 end 7
sum>M: excute: sum-6
sum 7 start 6 end 7
sum<M: excute: sum+8 end 7
sum 15 start 6 end 8
sum>M: excute: sum-7
sum 8 start 7 end 8
sum<M: excute: sum+9 end 8
sum 17 start 7 end 9
sum>M: excute: sum-8
sum 9 start 8 end 9
sum<M: excute: sum+10 end 9
sum 19 start 8 end 10
sum>M: excute: sum-9
sum 10 start 9 end 10
[10,10]
sum=M: sum 21 start 9 end 11
sum>M: excute: sum-10
sum 11 start 10 end 11
sum>M: excute: sum-11
sum 0 start 11 end 11
1 |
|
2059 *动态规划2
Look at 2037
1 |
|
LEECODE
二分查找
704. 二分查找
https://leetcode.cn/problems/binary-search/
1 | int search(vector<int>& nums, int target) { |
35. 搜索插入位置
https://leetcode.cn/problems/search-insert-position/
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Please use an algorithm with time complexity O(log n).
Input: nums = [1,3,5,6], target = 5
Output: 2
Input:: nums = [1,3,5,6], target = 2
Output: 1
Input:: nums = [1,3,5,6], target = 7
Output: 4
1 |
|
278. 第一个错误的版本
https://leetcode.cn/problems/first-bad-version/
You are a product manager and you are currently leading a team to develop a new product. Unfortunately, the latest version of your product failed quality testing. Since each version is developed based on the previous version, all versions after the wrong version are wrong.
Suppose you have n versions [1, 2, …, n] and you want to find the first wrong version that causes all subsequent versions to fail.
You can call the bool isBadVersion(version) interface to determine whether the version number version has an error in the unit test. Implement a function to find the first wrong version. You should minimize the number of calls to the API.
Input:n = 5, bad = 4
Output:4
Elaboration:
Call isBadVersion(3) -> false
Call isBadVersion(5) -> true
Call isBadVersion(4) -> true
Therefore,4 is the first bad version。
1 |
|
双指针
977. 有序数组的平方
https://leetcode.cn/problems/squares-of-a-sorted-array/
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
1 |
|
189.轮转数组
https://leetcode.cn/problems/rotate-array/
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
1 |
|
283. 移动零
https://leetcode.cn/problems/move-zeroes/
Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
1 | void moveZeroes(vector<int>& nums) { |
167. 两数之和 II - 输入有序数组
https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
1 |
|
344. 反转字符串
https://leetcode.cn/problems/reverse-string/
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: s = [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]
1 | void reverseString(vector<char>& s) { |
557. 反转字符串中的单词 III
https://leetcode.cn/problems/reverse-words-in-a-string-iii/
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Example 2:
Input: s = “God Ding”
Output: “doG gniD”
1 |
|
876. 链表的中间结点
https://leetcode.cn/problems/middle-of-the-linked-list/
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
1 | ListNode* middleNode(ListNode* head) { |
19. 删除链表的倒数第 N 个结点
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
- Define a node
fast, slow and dummy
,fast
is initialized by head ,slow
anddummy
will be initialized by the node before head, which is afake head
and don’t load any data .- The node fast will move to next node for n times to make sure the
fast
is n-nodes ahead ofslow
- Then let fast and slow move to their respective next node together 【fast=fast->next;slow=slow->next;】
- Skip the node that should be deleted. 【slow->next=slow->next->next;】
- return
dummy's next node.
【To make sure we are able to delete the head node】You have to consider the situation that the node-head is the n-th one like
[1], n=1
which will return[]
, that’s reason why we returndummy's next node
instead of returning head directly, otherwise, we will get[1]
instead of[]
1 | /** |
3. 无重复字符的最长子串
https://leetcode.cn/problems/longest-substring-without-repeating-characters/
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.
Let’s take the string in Example 1: abcabcbb
Take abcabcbb as an example, find the longest substring starting from each character and not containing repeated characters, then the longest string among them is the answer. For the string in Example 1, we list these results, where the selected characters and the longest string are indicated in brackets:Start with
(a)bcabcbb End with (abc)abcbb
Start with
a(b)cabcbb End with a(bca)bcbb
Start with
ab©abcbb End with ab(cab)cbb
Start with
abc(a)bcbb End with abc(abc)bb
Solution
In this solution, the purpose of
hash[d]--
is to decrease the occurrence of the character pointed by the left pointer in the hash table by 1, indicating that the character is no longer in the current window. In the sliding window, as the left pointer moves one position each time, the character it points to needs to be removed from the current window.For example, in the string
"abcbac"
, when the left pointer points to the second character “b”, the occurrences of characters “a” and “b” are recorded in the hash table, and the occurrence of character “b” is 2, indicating that there are duplicate characters in the current window. Therefore, the left pointer needs to move to the right, removing the first “b” from the window. At this point, the operationhash['b']--
is performed, decreasing the occurrence of character “b” by 1. The value corresponding to the element with the key “b” in the hash table becomes 1, indicating that the current window contains only one character “b”.
1 | class Solution { |
567. 字符串的排列
https://leetcode.cn/problems/permutation-in-string/
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1’s permutations is the substring of s2.
Example 1:
Input: s1 = “ab”, s2 = “eidbaooo”
Output: true
Explanation: s2 contains one permutation of s1 (“ba”).
Example 2:
Input: s1 = “ab”, s2 = “eidboaoo”
Output: false
- We create map<char,int>
need
to record the count of letter appears ins1
, and create map<char,int>window
to record the count of letter appears in thesliding window
- Start to search each letter(as variable
ch
) ins2
, if the letter is in s1(judge by need.count()), then we should update the tablewindow
, and add one inwindow[ch]
. Ifwindow[ch]
is equals toneed[ch]
,then we need to inhance the possibility of success by adding one invalid
.- If the length of the sliding window is greater than the length of
s1
, we need to deal with result and remove some illegal letter from the window.- If
valid
is equals toneed.size()
, which means we successfully match all letters froms1
ins2
.- If not, then we need to remove some illegal letters if they are in
s1
too, we need to reducevalid
by one ifwindow[d]==need[d]
, for example: If we consider s2=eidbxaaoo , s1=abb, there is a “x” between “b” and “aa” so we need to remove “b” from the window table, cuz it’s 100% illegal.
1 | class Solution { |
深度/广度遍历
733. 图像渲染
https://leetcode.cn/problems/flood-fill/
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
Return the modified image after performing the flood fill.
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Board
1 | vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) { |
Deep
As you can see, there almost no difference between dfs and bfs codes using queue and stack respectively, but the logic is a bit different.
1 | class Solution { |
695. 岛屿的最大面积
https://leetcode.cn/problems/max-area-of-island/
You are given an m x n binary matrix grid. An island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Example 1:
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
1 |
|
617. 合并二叉树
https://leetcode.cn/problems/merge-two-binary-trees/
BFS
1 | /** |
DFS
1 | /** |
DFS
1 | class Solution { |
542. 01 矩阵
https://leetcode.cn/problems/01-matrix/
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Start From Zero To One!!!!!
1 | class Solution { |
994. 腐烂的橘子
https://leetcode.cn/problems/rotting-oranges/
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
1 | class Solution { |
递归/回溯
21. 合并两个有序链表
https://leetcode.cn/problems/merge-two-sorted-lists/
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Iteration
1 | /** |
Recursion
We can find the miner one and merge it with the rest of elements and the rules as following.
- list1[0]+merge(list1[1:],list2) list1[0]<list2[0]
- list2[0]+merge(list1,list2[1:]) list1[0]>=list2[0]
1 | /** |
206.反转链表
https://leetcode.cn/problems/reverse-linked-list/
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Iteration
1 | /** |
77.组合
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.
Backtrack with pruning
path.size()
means the count of elements have been selected by us
(n-i+1)
is the count of rest of elementswe need to insure that the
path.size()
plus(n-i+1)
is more thanK
, otherwise , we can’t meet the condition.For each loop, i should start at
index
to avoid add the numbers that have been used.For each next backtracking , the
index
will start at(i+1)
to make sure there is no duplicate situation like (1,2) and (2,1) cuz we consider them as the same tuple.
1 | class Solution { |
216. 组合总和 III
https://leetcode.cn/problems/combination-sum-iii/
Find all valid combinations of k numbers that sum up to n such that the following conditions are true:
Only numbers 1 through 9 are used.
Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
Example 3:
Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations.
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.
1 | class Solution { |
动态规划
70. 爬楼梯
Source:https://leetcode.cn/problems/climbing-stairs/
Solution:https://programmercarl.com/0070.爬楼梯.html#思路
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
- Define a array dp,
dp[i]
means the ways to climb to thei
level- To reach to i level , we can climb from
i-1
ori-2
, so the ways toi
level equals to the ways toi-1
plus the ways toi-2
.dp[i]=dp[i-1]+dp[i-2]
- dp[0]=0, dp[1]=1, dp[2]=2
- because the
i
level dependent oni-1
andi-2
, so we traverse from front to rear
1 |
|
746. 使用最小花费爬楼梯
https://leetcode.cn/problems/min-cost-climbing-stairs/
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
1 |
|
62. 不同路径
https://leetcode.cn/problems/unique-paths/
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to 2 * 109.
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
- Right -> Down -> Down
- Down -> Down -> Right
- Down -> Right -> Down
1 |
|
63. 不同路径 II
https://leetcode.cn/problems/unique-paths-ii/
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.
Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The testcases are generated so that the answer will be less than or equal to 2 * 109.
When we initialize the first row and col at
dp
, we should stop initialize the rest of elements in the row or col when we meet a obstacle.And when we transerve the grid, if there’s a obstacle in [i][j], then we should set dp[i][j] as zero.
1 |
|
0-1背包
dp[i][j]
means the biggest value that we select a any count of items fromitem_0
toitem_i
and put them into a package whose capacity isj
if we don’t select item_i, then the maximum value of this package is
dp[i-1][j]
if we do select item_i, then the maximum value of this package is
value[i]+dp[i-1][j-weight[i]]
, which means we reserve some space(weight[i]
) foritem_i
and we will find the biggest value(dp[i-1][j-weight[i]]
) in such a condition , then we add the value ofitem_i
with that valueIn a short,
If we don’t select item_i,
dp[i][j]=dp[i-1][j]
If we select item_i,
dp[i][j]=dp[i-1][j-weight[i]]+value[i]
Then we should select the maximum one of the two value
max( dp[i-1][j],dp[i-1][j-weight[i]]+value[i] )
, it’s bit of long.
Weight | Value | |
---|---|---|
Item1 | 1 | 15 |
Item2 | 3 | 20 |
Item3 | 4 | 30 |
DP
0 | 1 | 2 | 3 | 4 | 5 | |
---|---|---|---|---|---|---|
Item1 | 0 | 15 | 15 | 15 | 15 | 15 |
Item2 | 0 | 15 | 15 | 20 | 35 | 35 |
Item3 | 0 | 15 | 15 | 20 | 35 | 45 |
1 | //Traverse items first ,however we also can traverse capacity first |
We also can compress dp into one-dimension
dp[j]=max(dp[j],dp[j-weight[i]]+value[i])
dp[j]
is still mean the maximum value inj
capacity, i means the item_iHere’s the code,
why we traverse from rear to front?
Once we traverse in positive order, the item_1 will be added multiple times!
For example:Item_1 :weight[0] = 1,[0] = 15
If we consider traverse in positive order, here’s the result.
dp[1] = dp[1 - weight[0]] + value[0] = 15
dp[2] = dp[2 - weight[0]] + value[0] = 30
dp[2] will get 30 which means we put item_1 twice!!!
how to initiazlie the dp
we should initialize
dp
with all zero , if we setdp
as other positive number like 10000, the initiazlied num will cover the new number we calculated in the future.dp[j]
- 10000 may will always bigger thandp[j-weight[i]]+value[i]
- other new number
1 |
|
416. 分割等和子集
https://leetcode.cn/problems/partition-equal-subset-sum/
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
This problem is a bit of special: weight[i]=value[i]
- First , we should calculate the sum of array, if sum%2==1, which means it can’t split to two sub-arrays.
- If not, the we set variable
target
=sum/2- Define a array dp,
dp[j]
means the maximum value in j capacity.- If
dp[j]==target
we can fill up the j capacity with some numbers whose sum is also j ,that means we can get two sub-arrays.
- For example, Input: nums = [1,5,11,5], we consider
dp[11]==target=11
as [1,5,5]=target=11 when we grap three number into package with 11 capacity and their sum is also 11.It’s a bit of puzzying, but it’s true.
1 |
|