当前位置:网站首页>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).
边栏推荐
- sqlilabs less-11~12
- Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
- sqlilabs less9
- Go integrates logrus to realize log printing
- Tdengine connector goes online Google Data Studio app store
- [R language data science]: common evaluation indicators of machine learning
- 我们该如何保护自己的密码?
- Oracle-数据库对象的使用
- This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI
- How to pass array parameters in get request
猜你喜欢

用对场景,事半功倍!TDengine 的窗口查询功能及使用场景全介绍

Texstudio tutorial

使用 Lambda 函数URL + CloudFront 实现S3镜像回源

So programmers make so much money doing private work? It's really delicious

phpcms实现订单直接支付宝支付功能

Play with mongodb - build a mongodb cluster

玩转MongoDB—搭建MongoDB集群

Websocket (simple experience version)

QT learning management system

【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统
随机推荐
QT learning management system
被裁三個月,面試到處碰壁,心態已經開始崩了
Learning to use livedata and ViewModel will make it easier for you to write business
Use lambda function URL + cloudfront to realize S3 image back to source
Etcd summary mechanism and usage scenarios
GET请求如何传递数组参数
Six years of technology iteration, challenges and exploration of Alibaba's globalization and compliance
Realize queue with stack and stack with queue (C language \leetcode\u 232+225)
“国防七子”经费暴增,清华足足362亿元,甩第二名101亿 |全国高校2022预算大公开...
[anwangbei 2021] Rev WP
自定义注解实现验证信息的功能
Play with mongodb - build a mongodb cluster
[241. Design priority for operation expression]
Scheme of printing statistical information in log
Introduction to distributed transactions (Seata)
C language course design topic
leetcode622. Design cycle queue (C language)
MySQL日志
程序设计的基本概念
玩转MongoDB—搭建MongoDB集群