current position：Home>Front end algorithm must brush question series [88]
Front end algorithm must brush question series [88]
20210827 00:15:43 【Wen bin Da Niao】
This is my participation 8 The fourth of the yuegengwen challenge 18 God , Check out the activity details ：8 Yuegengwen challenge
There's nothing in this series , It's pure leetcode Topic analysis , Don't seek to use a coquettish line or niche solution , But with clear code and simple enough ideas to help you clear up the topic . Let you no longer be afraid of the written test in the interview .
160. Search for a twodimensional matrix II (searcha2dmatrixii)
label
 secondary
subject
Write an efficient algorithm to search m x n matrix matrix One of the goals in target . The matrix has the following characteristics ：
The elements of each row are arranged in ascending order from left to right . The elements of each column are arranged in ascending order from top to bottom .
Example 1
Input ：matrix = [
[1,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]], target = 5
Output ：true
Copy code
Example 2
Input ：matrix = [
[1,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]], target = 20
Output ：false
Copy code
The basic idea
 The idea is actually very clear , It's like walking in a grid
 We can start at the bottom left , In this case 18 The number of
 Bigger than it , Take a step to the right , Smaller than it, take a step up until you find the answer
The writing method realizes
const searchMatrix = function(matrix, target) {
if (matrix.length === 0  matrix[0]?.length === 0) {
return false
}
// Boundary value calculation
let rows = matrix.length, cols = matrix[0]?.length
// Initialize the lower left corner as the starting point , The first column of the last row
let row = matrix.length  1, col = 0
// You can't go beyond the boundary
while (row >= 0 && col < cols) {
if (matrix[row][col] === target) {
return true
} else if (matrix[row][col] < target) {
// turn right
col++
} else {
// Go up
row
}
}
// Beyond the boundary
return false
}
let matrix = [
[1,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]], target = 22
console.log(searchMatrix(matrix, target))
Copy code
161. Complete square (perfectsquares)
label
 secondary
 mathematics
subject
Given a positive integer n, Find some perfect squares （ such as 1, 4, 9, 16, ...） Make their sum equal to n. You need to minimize the number of complete squares that make up the sum .
Give you an integer n , Return and for n Of the complete square of Minimum quantity .
Complete square It's an integer , Its value is equal to the square of another integer ; let me put it another way , Its value is equal to the product of the self multiplication of an integer . for example ,1、4、9 and 16 They're all perfect squares , and 3 and 11 No .
Example 1
Input ： n = 12
Output ： 3
explain ： 12 = 4 + 4 + 4
Copy code
Example 2
Input ： n = 13
Output ： 2
explain ： 13 = 4 + 9
Copy code
The basic idea
It's still our basic dynamic programming 3 Step train of thought .
State definition
our The goal is
Is to seek With n
The number is and
Of The least number of complete squares
Then set dp[i]
That is to say i The number is the minimum number of the complete square of the sum , that dp[n] That's our answer to this question
State shift
Let's start another j from the beginning , see dp[i  j * j] Actually Namely dp[i] Plus j The square of , So add... To the quantity 1
, The equation is
dp[i] = Math.min(dp[i], dp[i  j * j] + 1)
Does anyone say this will not happen , such as 12
Count to 12 = 9 + 3
=> dp[12] = dp[3] + 1
12 = 4 + 4 + 4
=> dp[12] = dp[8] + 1 = dp[4] + 1 + 1 = 1 + 1 + 1
We need to pay attention dp[4] = 1
, dp[3] = 3
So when we calculate the minimum , j The minimum value can still be calculated after the change .
The border
dp[i] The greatest satisfaction is actually all Split into 1 Add up
, i = 1 + 1 + 1+ ... + 1
(i individual 1)
The writing method realizes
const numSquares = function (n) {
let dp = new Array(n + 1).fill(0)
for (let i = 1; i < n + 1; i++) {
// This is a i Maximum case i = 1 + 1 + 1+ ... i individual 1
dp[i] = i
for (let j = 1; i >= j * j; j++) {
// Follow again dp[i  j * j] + 1 The biggest one At present j Round up the next smallest bit
dp[i] = Math.min(dp[i], dp[i  j * j] + 1)
}
}
return dp[n]
}
let n = 12
console.log(numSquares(n))
Copy code
In addition, I would like to recommend this series of articles to you , It's very simple , It is very useful for advanced students , Wall crack recommendation ！！！ Core concepts and algorithms
That's all for today , If you want to brush the topic with me, you can add my wechat Click here to make a friend Or Search my wechat infinity_9368
, You can chat and say Add my code " Heavenly King Gedi tiger " The next sentence is english
, Please send me the verification message presious tower shock the rever monster
, I see it through , After that, I'll do my best to help you , But pay attention to the way you ask questions , I suggest you read this article first ： The wisdom of asking questions
Reference resources
copyright notice
author[Wen bin Da Niao],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001541488u.html
The sidebar is recommended
 Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 20202021
 JS JavaScript how to get the subscript of a value in the array
 How to implement injection in vuex source code?
 JQuery operation select (value, setting, selected)
 One line of code teaches you how to advertise on Tanabata Valentine's Day  Animation 3D photo album (music + text) HTML + CSS + JavaScript
 An article disassembles the pyramid architecture behind the gamefi outbreak
 BEM  a frontend CSS naming methodology
 [vue3] encapsulate custom global plugins
 Error using swiper plugin in Vue
 Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like

Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei

He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?

Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste

Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy

Front end interview daily 3 + 1  day 858

Spring Webflux tutorial: how to build reactive web applications

[golang] walk into go language lesson 24 TCP highlevel operation

August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department

The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial

There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
 Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
 Introduction to flex flexible layout in CSS  learning notes
 CSS learning notes  Flex layout (Ruan Yifeng tutorial summary)
 Today, let's talk about the arrow function of ES6
 Some thoughts on small program development
 Talk about mobile terminal adaptation
 Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
 JS function scope, closure, let, const
 Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
 Unveil the mystery of ascension
 Asynchronous solution async await
 Analysis and expansion of Vue infinite scroll source code
 Compression webpack plugin first screen loading optimization
 Specific usage of vue3 video play plugin
 "The story of huiyeji"  people are always greedy, and fairies should be spotless!
 Installing Vue devtool for chrome and Firefox
 Basic usage of JS object
 1. JavaScript variable promotion mechanism
 Two easytouse animation JS that make the page move
 Front end Engineering  scaffold
 Java SQL Server intelligent fixed asset management, back end + front end + mobile end
 Mediator pattern of JavaScript Design Pattern
 Array de duplication problem solution  Nan recognition problem
 New choice for app development: building mobile applications using Vue native
 New gs8 Chengdu auto show announces interior Toyota technology blessing
 Vieira officially terminated his contract and left the team. The national security club sent blessings to him
 Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
 How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
 We are fearless in epidemic prevention and control  pay tribute to the frontline workers of epidemic prevention!
 Front end, netty framework tutorial
 Xiaomi 11  miui12.5  android11 solves the problem that the httpcanary certificate cannot be installed
 The wireless charging of SAIC Roewe rx5 plus is so easy to use!
 Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
 [25] typescript
 CSS transform Complete Guide (Second Edition) flight.archives 007
 Ajax foundation  HTTP foundation of interview essential knowledge
 Cloud lesson  explain in detail how Huawei cloud exclusive load balancing charges
 Decorator pattern of JavaScript Design Pattern
 [JS] 10. Closure application (loop processing)
 Left hand IRR, right hand NPV, master the password of getting rich