当前位置:网站首页>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 , Comparezero
andone
Size , 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];
}
}
边栏推荐
- Timing mechanism of LwIP
- ESP32-添加多目录的自定义组件
- Unable to create a folder to save the sketch: MKDIR sketch
- Live review | Ziya &ccf TF: Discussion on software supply chain risk management technology under cloud native scenario
- Keepalived 实现 Redis AutoFailover (RedisHA)17
- 持续交付-Blue Ocean 应用
- 接口测试框架实战(一) | Requests 与接口请求构造
- memcached基础
- 30《MySQL 教程》MySQL 存储引擎概述
- Keepalived 实现 Redis AutoFailover (RedisHA)16
猜你喜欢
自定义MVC(导成jar包)+与三层架构的区别+反射+面试题
Implementation of ARP module in LwIP
接口测试框架实战(一) | Requests 与接口请求构造
XSS攻击笔记(上)
解决STC8G1K08程序不能运行的问题和端口配置
世界很大,有人把二维码纹在脖子上
Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
Esp32-solo development tutorial to solve config_ FREERTOS_ UNICORE problem
做了两天的唯美蝴蝶动画
Amazon elasticache quickly builds a cache service cluster, which is fast
随机推荐
How to use ch423? Cheap domestic IO expansion chip
C#程序结构预览最基础入门
解决u8glib只显示一行文字或者不显示的问题
【毕业季】角色转换
Amazon ElastiCache 飞速搭建缓存服务集群,这才叫快
Analysis of ideal L9 product power: the price is 459800 yuan, the four cylinder engine is adopted, and the endurance is 1315km
Gaussian and Summary Stats
Break through the performance bottleneck of image recognition through rust language computing acceleration technology
Memcached foundation 7
使用NetworkX对社交网络进行系统的分析:Facebook网络分析案例
Implementation of ARP module in LwIP
Kept to implement redis autofailover (redisha) 16
IIS deploy static web site and FTP service
LeetCode 142. 环形链表 II
Solve the problem that stc8g1k08 program cannot run and port configuration
The world is very big. Some people tattoo QR codes on their necks
建模规范:环境设置
TopoLVM: 基于LVM的Kubernetes本地持久化方案,容量感知,动态创建PV,轻松使用本地磁盘
Interface test framework practice (I) | requests and interface request construction
在线文本数字识别列表求和工具