当前位置:网站首页>Day367: valid complete square
Day367: valid complete square
2022-06-23 01:22:00 【Shallow look】
List of articles
problem : Effective complete square number
Given a positive integer num , Write a function , If num It's a complete square , Then return to true , Otherwise return to false .
Advanced : Don't Use any built-in library functions , Such as sqrt .
source : Power button (LeetCode)
Train of thought : Brute force ergodic solution
For less than num Integer of from 1 To traverse the , Determine whether the square is equal to num, If equal to, return true, Otherwise return to false.
class Solution {
public boolean isPerfectSquare(int num) {
boolean result = false;
if (num==1) result = true;
for(int i=2; i < num/2+1; i++){
if(i*i==num){
result = true;
break;
}
}
return result;
}
}
shortcoming : When the integer is too large , Time limit exceeded .
Train of thought two : Dichotomy
- The root of a perfect square number x, Must be satisfied with 1 ≤ x ≤ n u m 1 \le x \le num 1≤x≤num, We use this interval as the search interval .
- left Start from the left side of the section ,right Start from the right side of the section , Calculate the median m i d = ( l e f t + r i g h t ) 2 mid=\frac{(left+right)}{2} mid=2(left+right)
- Perfect square heel x Must satisfy one of the three relationships , m i d = = x , m i d < x , m i d > x mid ==x ,mid <x, mid>x mid==x,mid<x,mid>x, So as left or right Update conditions for .
- The dichotomy is compared to the violent solution , The time complexity is reduced to some extent .
class Solution {
public boolean isPerfectSquare(int num) {
int left = 0;
int right = num;
boolean result = false;
while (left <= right){
int mid = (left + right)/2;
long mid_square = (long)mid*mid;
if(mid_square < num){
left = mid + 1;
}else if(mid_square > num){
right = mid - 1;
}
else{
result = true;
return result;
}
}
return result;
}
}
Train of thought three : Newton method
Newton's method is an approximate method to solve the zero point of a function , The iterative idea is as follows .
For the function f ( x ) f(x) f(x), Take any starting point ( x 0 , f ( x 0 ) ) (x0,f(x0)) (x0,f(x0)), Do the function at this point f ( x ) f(x) f(x) The tangent of , Tangent and x Axis intersection point x 1 x1 x1 Is the abscissa of the point to be updated next time , comparison x 0 x0 x0 for , x 1 x1 x1 Closer to zero , After many iterations , It can be approximated as point x 1 x1 x1 Approaching the zero of a function .
Ideas :
In this case f ( x ) = x 2 − n u m f(x)=x^2-num f(x)=x2−num
Update formula x i + 1 = ( x i + n u m / x i ) / 2 x_{i+1}=(x_i+num/{x_i})/2 xi+1=(xi+num/xi)/2
The end condition : We think that when the results of two adjacent iterations are similar , It can be considered close enough to zero .
Code :
class Solution {
public boolean isPerfectSquare(int num) {
double x0 = num;
double x1 = 0;
while (true){
x1 = (x0 + num/x0)/2;
if (x0 - x1 < 1e-1)
break;
x0 = x1;
}
x1 = (int)x1;
return x1*x1 == num;
}
}
Reference resources : Try to answer the official questions
边栏推荐
- Have you stepped on these pits? Use caution when creating indexes on time type columns
- Huawei cloud recruits partners in the field of industrial intelligence to provide strong support + commercial realization
- Vector 1 (classes and objects)
- SwiftUI Swift 教程之 14 个有用的数组运算符
- Ros2 summer school 2022 transfer-
- Found several packages [runtime, main] in ‘/usr/local/Cellar/go/1.18/libexec/src/runtime;
- Explain the startup process of opengauss multithreading architecture in detail
- A blog allows you to understand the use of material design
- Prevent others from using the browser to debug
- Xiaobai operates win10 to expand Disk C (allocate disk D memory to Disk C) and the test is valid for many times
猜你喜欢

Local deployment and problem solving of IIS in ArcGIS JS 4.23

Explain the startup process of opengauss multithreading architecture in detail

一文读懂基于Redis的Amazon MemoryDB数据库

Steps to implement a container global component

Tidb monitoring upgrade: a long way to solve panic

贵金属现货白银如何呢?

Installation record of ros1noetic in Win 11

New progress in the construction of meituan's Flink based real-time data warehouse platform
Yyds dry goods counting tail recursion is better than recursion

LeetCode 206. Reverse linked list (iteration + recursion)
随机推荐
Shell logs and printouts
Shell 查看帮助
What is the storage structure and mode of data in the database?
最安全的现货白银的心理分析
3DMAX modeling notes (I): introducing 3DMAX and creating the first model Hello World
Is it safe for Hongyuan futures to open an account? Can Hongyuan futures company reduce the handling fee?
时间复杂度
总体标准差和样本标准差
LeetCode 206. Reverse linked list (iteration + recursion)
Sfod: passive domain adaptation and upgrade optimization, making the detection model easier to adapt to new data
Cadence spb17.4 - Allegro - optimiser la spécification de l'angle de connexion de la polyligne pour une seule ligne électrique - polyligne à arc
Vector 3 (static member)
LINQ query
[Title Fine brushing] 2023 Hesai FPGA
贵金属现货白银如何呢?
How to solve the problem that easycvr does not display the interface when RTMP streaming is used?
Installing MySQL for Linux
You can also do NLP (classification)
JS prevent the PC side from copying correct links
[launch] redis Series 2: data persistence to improve availability