当前位置:网站首页>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).
边栏推荐
- Research Report on the development trend and competitive strategy of the global ultrasonic scalpel system industry
- Journal MySQL
- Halo effect - who says that those with light on their heads are heroes
- Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
- 既不是研发顶尖高手,也不是销售大牛,为何偏偏获得 2 万 RMB 的首个涛思文化奖?
- [R language data science]: common evaluation indicators of machine learning
- sqlilabs less10
- 使用 Lambda 函数URL + CloudFront 实现S3镜像回源
- How can we protect our passwords?
- Learning to use livedata and ViewModel will make it easier for you to write business
猜你喜欢

逻辑是个好东西

用对场景,事半功倍!TDengine 的窗口查询功能及使用场景全介绍
![[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

Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server

QT community management system

sqlilabs less10

Logic is a good thing

Animesr: learnable degradation operator and new real world animation VSR dataset

WebSocket(简单体验版)
![[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial](/img/44/b65aaf11b1e632f2dab55b6fc699f6.jpg)
[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial
随机推荐
Research Report on the development trend and competitive strategy of the global ultrasonic scalpel system industry
[sword finger offer] 55 - I. depth of binary tree
【商业终端仿真解决方案】上海道宁为您带来Georgia介绍、试用、教程
B站被骂上了热搜。。
玩转gRPC—不同编程语言间通信
光環效應——誰說頭上有光的就算英雄
微服务大行其道的今天,Service Mesh是怎样一种存在?
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
SWT/ANR问题--如何捕获性能的trace
Après avoir été licencié pendant trois mois, l'entrevue s'est effondrée et l'état d'esprit a commencé à s'effondrer.
佩服,阿里女程序卧底 500 多个黑产群……
Use the right scene, get twice the result with half the effort! Full introduction to the window query function and usage scenarios of tdengine
原来程序员搞私活这么赚钱?真的太香了
Research Report on the development trend and competitive strategy of the global pipeline robot inspection camera industry
深度合作 | 涛思数据携手长虹佳华为中国区客户提供 TDengine 强大企业级产品与完善服务保障
小程序- view中多个text换行
Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
Texstudio tutorial
Distributed dynamic (collaborative) rendering / function runtime based on computing power driven, data and function collaboration
MySQL日志