当前位置:网站首页>Leetcode (69) -- square root of X
Leetcode (69) -- square root of X
2022-07-01 14:14:00 【SmileGuy17】
Leetcode(69)——x The square root of
subject
Give you a nonnegative integer x , Calculate and return x Of Arithmetical square root .
Because the return type is an integer , Results are retained only Integral part , The decimal part will be Give up .
Be careful : No built-in exponential functions and operators are allowed , for example pow(x, 0.5) perhaps x ** 0.5 .
Example 1:
Input :x = 4
Output :2
Example 2:
Input :x = 8
Output :2
explain :8 The arithmetic square root of is 2.82842…, Because the return type is an integer , The decimal part will be removed .
Tips :
- 0 0 0 <= x <= 2 31 − 1 2^{31 - 1} 231−1
Answer key
Method 1 : Brute force
Ideas
because x x x The value rounded down by the arithmetic square root of must be [ 0 , x ] [0, x] [0,x] in , So directly and violently from 0 0 0 Traversing x x x, Until you find the first square greater than x x x Value , It subtracts 1 1 1 Is the value we want to find .
Code implementation
My own :
class Solution {
public:
int mySqrt(int x) {
long n;
for(n = 0; n*n <= x; n++);
return n-1;
}
};
Complexity analysis
Time complexity : O ( x ) O(x) O(x), The worst case is from 0 0 0 Find the x x x Just found it
Spatial complexity : O ( 1 ) O(1) O(1).
Method 2 : Two points search
Ideas
because x x x The integer part of the square root ans \textit{ans} ans yes Satisfy k 2 ≤ x k^2 \leq x k2≤x Maximum k k k value , So we can do something about k k k Do a binary search , To get the answer .
The lower bound of binary search is 0 0 0, The upper bound can be roughly set to x x x. In each step of binary search , We just need to compare the intermediate elements mid \textit{mid} mid The sum of the squares of x x x The size of the relationship , The range of the upper and lower bounds is adjusted by comparing the results . Because all our operations are integer operations , There will be no error , So when you get the final answer ans \textit{ans} ans after , There is no need to try again ans + 1 \textit{ans} + 1 ans+1 了 .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long long)mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
};
my :
class Solution {
public:
int mySqrt(int x) {
long min = 0, max = x, mid;
while(min <= max){
mid = (min + max)/2;
if(mid*mid < x){
if((mid+1)*(mid+1) > x) break;
else min = mid+1;
}else if(mid*mid > x) max = mid-1;
else break;
}
return mid;
}
};
Complexity analysis
Time complexity : O ( l o g x ) O(logx) O(logx), That is, the number of times needed for binary search .
Spatial complexity : O ( 1 ) O(1) O(1).
Method 3 : Newton's iteration
Ideas
Newton's iteration It is a method that can be used to quickly solve the zero point of a function .
For narrative purposes , We use it C C C Represents the integer for which the square root is to be found . obviously , C C C The square root of is a function
y = f ( x ) = x 2 − C y = f(x) = x^2 - C y=f(x)=x2−C
Zero point of .
The essence of Newton's iterative method With the help of Taylor series , Approaching zero point quickly from initial value . Let's take one x 0 x_0 x0 As an initial value , In each iteration , We find the point on the graph of the function ( x i , f ( x i ) ) (x_i, f(x_i)) (xi,f(xi)), Make a slope across the point as the derivative of the point f ′ ( x i ) f'(x_i) f′(xi) The straight line of , The point of intersection with the horizontal axis is marked as x i + 1 x_{i+1} xi+1. x i + 1 x_{i+1} xi+1 Compare with x i x_i xi It's closer to zero . After many iterations , We can get a point of intersection very close to zero . The figure below shows the results from x 0 x_0 x0 Start iterating twice , obtain x 1 x_1 x1 and x 2 x_2 x2 The process of .

Algorithm
We choose x 0 = C x_0 = C x0=C As an initial value .
In each iteration , We pass through the current intersection x i x_i xi, Find the point on the function image ( x i , x i 2 − C ) (x_i, x_i^2 - C) (xi,xi2−C), Make a slope of f ′ ( x i ) = 2 x i f'(x_i) = 2x_i f′(xi)=2xi The straight line of , The equation of a straight line is :
y l = 2 x i ( x − x i ) + x i 2 − C = 2 x i x − ( x i 2 + C ) \begin{aligned} y_l &= 2x_i(x - x_i) + x_i^2 - C \\ &= 2x_ix - (x_i^2 + C) \end{aligned} yl=2xi(x−xi)+xi2−C=2xix−(xi2+C)
The intersection with the horizontal axis is the equation 2 x i x − ( x i 2 + C ) = 0 2x_ix - (x_i^2 + C) = 0 2xix−(xi2+C)=0 Solution , This is the new iteration result x i + 1 x_{i+1} xi+1:
x i + 1 = 1 2 ( x i + C x i ) x_{i+1} = \frac{1}{2}\left(x_i + \frac{C}{x_i}\right) xi+1=21(xi+xiC)
It's going on k k k After iterations , x k x_k xk And the real zero C \sqrt{C} C Close enough to , That's the answer .
details
- Why choose x 0 = C x_0 = C x0=C As an initial value ?
because y = x 2 − C y = x^2 - C y=x2−C There are two zeros − C -\sqrt{C} −C and C \sqrt{C} C. If we take a smaller initial value , It may iterate to − C -\sqrt{C} −C This zero point , What we hope to find is C \sqrt{C} C This zero point . So choose x 0 = C x_0 = C x0=C As an initial value , Every iteration has x i + 1 < x i x_{i+1} < x_i xi+1<xi, zero C \sqrt{C} C On its left , So we must iterate to this zero .
- When does the iteration end ?
After each iteration , We will all be further away from zero , So when the intersection of two adjacent iterations is very close , We can conclude , The result at this time is enough for us to get the answer . Generally speaking , We can judge whether the difference between the results of two adjacent iterations is less than a minimal non negative number ϵ \epsilon ϵ, among ϵ \epsilon ϵ Generally, you can take 1 0 − 6 10^{-6} 10−6 or 1 0 − 7 10^{-7} 10−7.
- How to get the final answer through the approximate zero obtained by iteration ?
because y = f ( x ) y = f(x) y=f(x) stay [ C , + ∞ ] [\sqrt{C}, +\infty] [C,+∞] Is a convex function (convex function) And constant greater than or equal to zero , So as long as we choose the initial value x 0 x_0 x0 Greater than or equal to C \sqrt{C} C, The result of each iteration x i x_i xi Will always be greater than or equal to C \sqrt{C} C. So long as ϵ \epsilon ϵ The choice is small enough , Final result x k x_k xk It will only be slightly greater than the real zero C \sqrt{C} C. Given in the title 32 Bit integer range , The following will not happen :
The real zero is n − 1 / 2 ϵ n−1/2\epsilon n−1/2ϵ, among n n n Is a positive integer , And the result of our iteration is n + 1 / 2 ϵ n+1/2\epsilon n+1/2ϵ. After reserving the integer part of the result, we get n n n, But the correct result is n − 1 n - 1 n−1.
Code implementation
Leetcode Official explanation :
class Solution {
public:
int mySqrt(int x) {
long ans = x;
while(ans * ans > x)
ans = (ans + x/ans)/2;
return ans;
}
};
Complexity analysis
Time complexity : O ( log x ) O(\log x) O(logx), This method is quadratic convergent , Faster than binary search .
Spatial complexity : O ( 1 ) O(1) O(1).
Method four : Pocket calculator algorithm
Ideas
「 Pocket calculator algorithm 」 Is an exponential function exp \exp exp Logarithmic function ln \ln ln Instead of the square root function . We can use finite mathematical functions , Get the result we want to calculate .
We will x \sqrt{x} x Written as a power x 1 / 2 x^{1/2} x1/2, Then use the natural logarithm e e e Change the bottom , You can get
x = x 1 / 2 = ( e ln x ) 1 / 2 = e 1 2 ln x \sqrt{x} = x^{1/2} = (e ^ {\ln x})^{1/2} = e^{\frac{1}{2} \ln x} x=x1/2=(elnx)1/2=e21lnx
So we can get x \sqrt{x} x The value of the .
Be careful : Because the computer cannot store the exact value of floating point numbers ( For the storage method of floating point numbers, please refer to IEEE 754, No more details here ), The parameters and return values of exponential function and logarithmic function are floating-point numbers , Therefore, there will be errors in the operation process . For example, when x = 2147395600x=2147395600 when , e 1 2 ln x e^{\frac{1}{2} \ln x} e21lnx Calculation results and correct values 4634046340 Difference between 1 0 − 11 10^{-11} 10−11, In this way, when taking the integer part of the result , You'll get 4633946339 The wrong result .
So in the integer part of the result ans \textit{ans} ans after , We should find out ans \textit{ans} ans And ans + 1 \textit{ans} + 1 ans+1 Which one of them is the real answer .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int mySqrt(int x) {
if (x == 0) {
return 0;
}
int ans = exp(0.5 * log(x));
return ((long long)(ans + 1) * (ans + 1) <= x ? ans + 1 : ans);
}
};
Complexity analysis
Time complexity : O ( 1 ) O(1) O(1), Because of the built-in exp Function and log Functions are generally fast , Here we regard its complexity as O ( 1 ) O(1) O(1).
Spatial complexity : O ( 1 ) O(1) O(1).
边栏推荐
- Uni app realizes advertisement scroll bar
- Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server
- App自动化测试开元平台Appium-runner
- [sword finger offer] 55 - I. depth of binary tree
- Use lambda function URL + cloudfront to realize S3 image back to source
- QT学习管理系统
- sqlilabs less13
- After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse
- 【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
- Applet - applet chart Library (F2 chart Library)
猜你喜欢

Phpcms realizes the direct Alipay payment function of orders

使用CMD修复和恢复病毒感染文件

Oracle-数据库对象的使用
![[安网杯 2021] REV WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[安网杯 2021] REV WP

用栈实现队列、用队列实现栈(C语言_leetcode_232+225)
![[repair version] imitating the template of I love watching movies website / template of ocean CMS film and television system](/img/fa/15b1cc3a8a723ff34eb457af9f701e.jpg)
[repair version] imitating the template of I love watching movies website / template of ocean CMS film and television system

“国防七子”经费暴增,清华足足362亿元,甩第二名101亿 |全国高校2022预算大公开...

What "hard core innovations" does Intel have in the first half of 2022? Just look at this picture!

【Flask】Flask启程与实现一个基于Flask的最小应用程序

TDengine 连接器上线 Google Data Studio 应用商店
随机推荐
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
Animesr: learnable degradation operator and new real world animation VSR dataset
Basic operation of queue (implemented in C language)
QT community management system
uni-app实现广告滚动条
Uni app realizes advertisement scroll bar
This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI
[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial
程序设计的基本概念
【Flask】Flask启程与实现一个基于Flask的最小应用程序
【剑指Offer】54. 二叉搜索树的第k大节点
Play with grpc - communication between different programming languages
逻辑是个好东西
leetcode622.设计循环队列(C语言)
In depth cooperation | Taosi data cooperates with changhongjia Huawei customers in China to provide tdengine with powerful enterprise level products and perfect service guarantee
Research Report on the development trend and competitive strategy of the global facial wrinkle removal and beauty instrument industry
使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器
Logic is a good thing
When the main process architecture game, to prevent calls everywhere to reduce coupling, how to open the interface to others to call?
Leetcode(69)——x 的平方根