69. Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Solution in C++:
- 关键点:不能暴力,得使用数学方法或者算法
- 思路:由于本人的数学基本都忘干净了,牛顿迭代也是完全想不起来,然后以为暴力可以通过,发现time limited exceeded之后愣住了。也没有把这个问题转换为其实就是查找问题,并且是已经排好序的,可以使用二分方法。以下记录以下我的错误方法以及推荐的实现方法。
Time limited Exceeded方法
int mySqrt(int x) {
// time limited exceeded
int i;
for(i = 0 ; i <= x; ++i)
{
if (i*i > x)
return i - 1;
else if(i*i == x)
return i;
}
return i;
}
牛顿迭代方法
int mySqrt(int x) {
long r = x; // int 会溢出
while (r*r > x)
r = (r + x/r) / 2;
return r;
}
二分查找方法
if(x == 0 || x== 1)
return x;
int left = 1, right = x;
while(left <= right){
int mid = (left + right) / 2;
if (mid == x / mid)
return mid;
else if(mid < x / mid)
left = mid + 1;
else if (mid > x/mid)
right = mid - 1;
}
return left - 1; // 因为退出while循环的时候必定是left > right的时候,所以需要-1
70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
Solution in C++:
- 关键点:思路清晰,了解递归、动态规划或者斐波拉契数列即可
- 思路:最开始是暴力想法,但是由于好久没写递归了,递归的式子想的也不是很对再加上上一题超时的阴影,导致我没有动手。直接去看了soulution。然后自己实现了动态规划以及斐波拉契公式两种方法。
动态规划
int climbStairs(int n) {
if (n == 1)
return n;
vector<int> dp{0};
dp.push_back(1);
dp.push_back(2);
int i;
for (i = 3; i <= n; ++i)
dp.push_back(dp[i-1] + dp[i-2]);
return dp[n];
}
斐波拉契公式: F n F_{n} Fn= 1 5 \frac{1}{\sqrt{5}} 51(( 1 + 5 2 ) n + 1 \frac{1+\sqrt{5}}{2})^{n+1} 21+5)n+1-( 1 − 5 2 ) n + 1 \frac{1-\sqrt{5}}{2})^{n+1} 21−5)n+1)
double sqrt5 = sqrt(5);
double fin = pow((1+sqrt5)/2,n+1) - pow((1-sqrt5)/2,n+1);
return (int)(fin/sqrt5);
小结
今天刷题不知道怎么说了,感觉满满的挫败感啊,不过也确实补充了很多知识,现在感觉自己慢慢积攒的知识越来越多没有去细究了,希望以后能够在反复训练之中慢慢越来越熟练。
- 牛顿迭代法
- 二分查找
- 动态规划
- 斐波拉契数列