当前位置:网站首页>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).
边栏推荐
- El form item regular verification
- 8款最佳实践,保护你的 IaC 安全!
- Journal MySQL
- sqlilabs less9
- sqlilabs less13
- Summary of leetcode's dynamic programming 5
- 既不是研发顶尖高手,也不是销售大牛,为何偏偏获得 2 万 RMB 的首个涛思文化奖?
- 开源实习经验分享:openEuler软件包加固测试
- That hard-working student failed the college entrance examination... Don't panic! You have another chance to counter attack!
- Understand the window query function of tdengine in one article
猜你喜欢
[241. Design priority for operation expression]
phpcms实现订单直接支付宝支付功能
WebSocket(简单体验版)
Play with grpc - communication between different programming languages
How will the surging tide of digitalization overturn the future?
[安网杯 2021] REV WP
sqlilabs less9
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
Open source internship experience sharing: openeuler software package reinforcement test
That hard-working student failed the college entrance examination... Don't panic! You have another chance to counter attack!
随机推荐
佩服,阿里女程序卧底 500 多个黑产群……
Go integrates logrus to realize log printing
Station B was scolded on the hot search..
Research Report on the development trend and competitive strategy of the global facial wrinkle removal and beauty instrument industry
After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse
Basis of target detection (NMS)
小程序- view中多个text换行
TDengine 连接器上线 Google Data Studio 应用商店
App自动化测试开元平台Appium-runner
Six years of technology iteration, challenges and exploration of Alibaba's globalization and compliance
Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial
sqlilabs less-8
程序设计的基本概念
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
我们该如何保护自己的密码?
Provincial election + noi Part VIII fraction theory
A new book by teacher Zhang Yujin of Tsinghua University: 2D vision system and image technology (five copies will be sent at the end of the article)
[Jianzhi offer] 54 The k-th node of binary search tree
When the main process architecture game, to prevent calls everywhere to reduce coupling, how to open the interface to others to call?