当前位置:网站首页>Daily question brushing record (V)
Daily question brushing record (V)
2022-06-27 01:17:00 【Unique Hami melon】
List of articles
The first question is : The longest continuous sequence
LeetCode: The finger of the sword Offer II 119. The longest continuous sequence
describe :
Given an array of unsorted integers nums , Find the longest sequence of consecutive numbers ( Sequence elements are not required to be contiguous in the original array ) The length of .
Their thinking :
- First, put the array elements into HashSet in
- Find current element , To determine if anyone is younger than him 1 The elements of
- without . Then judge whether anyone is older than him 1 The elements of , loop , Record how many elements are satisfied .
- If there is , Go directly to the next cycle .
- Returns the maximum number of times in the record
Code implementation :
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
// The first iteration stores the array in the hash
for(int val : nums) {
set.add(val);
}
int ans = 0;
for(int val : nums) {
// Determine whether there is any element smaller than the current one 1 Of
if(!set.contains(val-1)){
// There is nothing smaller than the current element 1 Of
int ret = val + 1;
int count = 1;
// there count by 1, Because I have to count myself
while (set.contains(ret)) {
count++;
ret++;
}
ans = Math.max(ans,count);
}
}
return ans;
}
}
The second question is : The minimum number of coins
LeetCode: The finger of the sword Offer II 103. The minimum number of coins
describe :
Give coins of different denominations coins And a total amount amount. Write a function to calculate the minimum number of coins needed to make up the total amount . If no combination of coins can make up the total amount , return -1.
You can think of the number of coins of each kind as infinite .
Their thinking :
Dynamic planning ideas :
- state F(i) : Indicates that the current i Minimum number of coins per coin
- State transition equation : F[i] = Math.min(F[i],F[i-coins[j]]+1)
- The initial state : F(0) = 0;
- Return results : F(amount)
Code implementation :
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount+1];
// amount+1 Can avoid overflow
Arrays.fill(dp,amount+1);
dp[0] = 0;
for(int i = 1; i < amount+1; i++) {
for(int j = 0; j < coins.length; j++) {
// The denomination of coins should be less than the total amount
if(coins[j] <= i) {
dp[i] = Math.min(dp[i],dp[i-coins[j]]+1);
}
}
}
// If amount The value of the subscript does not change , Can't come up with
return dp[amount] > amount ? -1 : dp[amount];
}
}
Third question : The least cost of climbing stairs
LeetCode: The finger of the sword Offer II 088. The least cost of climbing stairs
describe :
Each subscript of the array acts as a ladder , The first i A ladder corresponds to a non negative amount of physical expenditure cost[i]( Subscript from 0 Start ).
Each time you climb a ladder, you have to spend the corresponding physical strength , Once you've paid for your strength , You can choose to climb up one step or two steps .
Please find out the lowest cost to reach the top of the floor . At the beginning , You can choose from the subscript to 0 or 1 As the initial step .

Their thinking :
Dynamic planning ideas :
- state F(i) : It means to climb to the first i The minimum cost of a staircase
- State transition equation : F[i] = Math.min(F[i-2],F[i-1])+cost[i];
- The initial state : F(0) = cost[0];F(1) = cost[1]
- Return results : Math.min( F(len-1) , F(len-2) )
Because you can jump here 1 Step or 2 Step , Therefore, it is necessary to judge the first two minimum costs , Then add the current cost
The return result depends on Who is the smaller of the last step or the penultimate step
Code implementation :
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length];
// initialization
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.length; i++) {
dp[i] = Math.min(dp[i-2],dp[i-1])+cost[i];
}
return Math.min(dp[cost.length-1],dp[cost.length-2]);
}
}
Fourth question : Flip the character
LeetCode: The finger of the sword Offer II 092. Flip the character
describe :
If one consists of ‘0’ and ‘1’ Composed string , With some ‘0’( There may be no ‘0’) Followed by some ‘1’( Or maybe not ‘1’) In the form of , Then the string is Monotone increasing Of .
We give a character ‘0’ and ‘1’ Composed string s, We can take any ‘0’ Flip to ‘1’ Or will ‘1’ Flip to ‘0’.
Return to make s Monotone increasing Minimum number of flips .
Their thinking :
- Traversal string s
- Determine whether the current character is 0
If 0, Just recordzero = Math.min(one, zero+1)Because when the initial state , No, 1 When , Start recording 0 Will waste , To record when 1 sometimes . Use here min The way to judge .
If 1, Just recordone++
End of traversal , ComparezeroandoneSize , Return to the smaller
Code implementation :
Fifth question : Paint the house
LeetCode: The finger of the sword Offer II 091. Paint the house
describe :
If there is a row of houses , common n individual , Every house can be painted red 、 One of the three colors blue or green , You need to paint all the houses and make the two adjacent houses not the same color .
Of course , Because the prices of different colors of paint on the market are different , So the cost of painting the house in different colors is different . The cost of painting each house in a different color is one n x 3 Positive integer matrix of costs To represent the .
for example ,costs[0][0] It means the first one 0 The cost of painting the house red ;costs[1][2] It means the first one 1 The cost of painting the house green , And so on .
Please calculate the minimum cost of painting all the houses .
Their thinking :
There are requirements in the title : Paint all the houses and make them adjacent Two houses cannot be the same color
cost[i][0] = cost[i-1][1]+cost[i-1][2], In this way , Calculate the minimum value of each layer using the current color .
Return to the last layer , The youngest one
Code implementation :
class Solution {
public int minCost(int[][] costs) {
for(int i = 1; i < costs.length; i++){
costs[i][0] += Math.min(costs[i-1][1],costs[i-1][2]);
costs[i][1] += Math.min(costs[i-1][0],costs[i-1][2]);
costs[i][2] += Math.min(costs[i-1][1],costs[i-1][0]);
}
return Math.min(costs[costs.length-1][0],Math.min(costs[costs.length-1][1],costs[costs.length-1][2]));
}
}
Sixth question : House theft
LeetCode: The finger of the sword Offer II 089. House theft
describe :
A professional thief , Plan to steal houses along the street . There is a certain amount of cash in every room , The only constraint on thieves' theft is that adjacent houses are equipped with interconnected anti-theft systems , If two adjacent houses are broken into by thieves on the same night , The system will automatically alarm .
Given an array of non negative integers representing the storage amount of each house nums , Please calculate Without triggering the alarm , The maximum amount that can be stolen overnight .
Their thinking :
Dynamic planning ideas :
- state F(i) : It means stealing i Maximum amount when subscribing
- State transition equation : F[i] = Math.max( F[i-2] + nums[i], F[i-1]) ;
- The initial state : F(0) = nums[0], F(1) = Math.max(nums[0],nums[1])
- Return results : F(len-1)
Code implementation :
class Solution {
public int rob(int[] nums) {
if(nums.length == 1) return nums[0];
int[] dp = new int[nums.length];
dp[0] = nums[0];
dp[1] = Math.max(nums[0],nums[1]);
for(int i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);
}
return dp[nums.length-1];
}
}
边栏推荐
- NLP: brief introduction of transformer in NLP natural language field (pre training technology), NLP model development (elmo/gpt/bert/mt-dnn/xlnet/roberta/albert), detailed introduction to classic case
- Amazon elasticache quickly builds a cache service cluster, which is fast
- 07 | workflow design: how to design a reasonable multi person development mode?
- Visual introduction to Matplotlib and plotnine
- IIS 部署静态网站和 FTP 服务
- Two days of beautiful butterfly animation
- Bootstrapblazor + FreeSQL actual combat chart usage (2)
- ESP32-添加多目录的自定义组件
- Flink 实战问题(七):No Watermark(Watermarks are only available EventTime is used)
- XSS笔记(下)
猜你喜欢

理想L9产品力分析:售价45.98万,采用四缸发动机,续航1315公里

Lambda expression

ArcGIS 镶嵌数据集切片丢失问题处理

Analysis of ideal L9 product power: the price is 459800 yuan, the four cylinder engine is adopted, and the endurance is 1315km

乔治·华盛顿大学 : Hanhan Zhou | PAC:多智能体强化学习中具有反事实预测的辅助价值因子分解

ML:机器学习工程化之团队十大角色背景、职责、产出物划分之详细攻略

Operating instructions and Q & A of cec-i China learning machine
![寻找旋转排序数组中的最小值 II[经典抽象二分 + 如何破局左中右三者相等]](/img/75/05d5765588dfde971167fbc72e2aa8.png)
寻找旋转排序数组中的最小值 II[经典抽象二分 + 如何破局左中右三者相等]

Review the old and know the new -- constant renewal at normal temperature

The world is very big. Some people tattoo QR codes on their necks
随机推荐
These 10 copywriting artifacts help you speed up the code. Are you still worried that you can't write a copywriting for US media?
自定义JSP[if,foreach,数据,select]标签
大白话高并发(一)
How to measure the thickness of glass substrate by spectral confocal
ESP32实验-自建web服务器配网02
Memcached foundation 5
Solve the problem that only one line of text is displayed or not displayed in u8glib
Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
memcached基础3
XSS notes (Part 2)
CLIP:从自然语言监督中学习可迁移的视觉模型
接口测试框架实战(一) | Requests 与接口请求构造
ArcGIS 镶嵌数据集切片丢失问题处理
30 MySQL tutorial MySQL storage engine overview
Memcached Foundation
XSS攻击笔记(上)
Esp32 experiment - self built web server distribution network 02
3 - wire SPI Screen Drive
Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
Interface test framework practice (I) | requests and interface request construction