当前位置:网站首页>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];
}
}
边栏推荐
- Is it safe to open a securities account online? Is it reliable to speculate in stocks by mobile phone
- Beyond lithium battery -- the concept of battery in the future
- What are the skills and methods for slip ring installation
- Solve the problem that only one line of text is displayed or not displayed in u8glib
- CLIP:从自然语言监督中学习可迁移的视觉模型
- Xiaobai looks at MySQL -- installing MySQL in Windows Environment
- 07 | workflow design: how to design a reasonable multi person development mode?
- 解决unable to create a folder to save the sketch: mkdir sketch
- 超越锂电池——未来电池的概念
- Record a bug caused by a line break
猜你喜欢

Esp32-solo development tutorial to solve config_ FREERTOS_ UNICORE problem

建模规范:环境设置

Hid device descriptor and keyboard key value corresponding coding table in USB protocol

一键加速索尼相机SD卡文件的复制操作,文件操作批处理教程

Flink 实战问题(七):No Watermark(Watermarks are only available EventTime is used)

30《MySQL 教程》MySQL 存储引擎概述

buuctf-pwn write-ups (6)
![Count the logarithm of points that cannot reach each other in an undirected graph [classic adjacency table building +dfs Statistics - > query set optimization] [query set manual / write details]](/img/cc/a0be58eddc72c22a9a6ee5c61eb81a.png)
Count the logarithm of points that cannot reach each other in an undirected graph [classic adjacency table building +dfs Statistics - > query set optimization] [query set manual / write details]

IIS 部署静态网站和 FTP 服务

光谱共焦如何测量玻璃基板厚度
随机推荐
LeetCode 142. 环形链表 II
leetcode 1143. Longest Commom Subsequence 最长公共子序列(中等)
Processing of slice loss in ArcGIS mosaic dataset
IIS deploy static web site and FTP service
Weibo comments on high performance and high availability architecture
Skills needing attention in selection and purchase of slip ring
UVM中config_db机制的使用方法
XSS攻击笔记(上)
Kept to implement redis autofailover (redisha) 14
buuctf-pwn write-ups (6)
Hid device descriptor and keyboard key value corresponding coding table in USB protocol
使用NetworkX对社交网络进行系统的分析:Facebook网络分析案例
Statistical Hypothesis Testing
光谱共焦如何测量玻璃基板厚度
ESP32-添加多目录的自定义组件
Flink practical problems (VII): no watermark (watermarks are only available eventtime is used)
Great vernacular with high concurrency (I)
memcached基础4
Operating instructions and Q & A of cec-i China learning machine
What is the difference between the working principle of gas-liquid slip ring and other slip rings