[日常刷题]LeetCode第九天

编程入门 行业动态 更新时间:2024-10-26 02:25:56

[<a href=https://www.elefans.com/category/jswz/34/1770030.html style=日常刷题]LeetCode第九天"/>

[日常刷题]LeetCode第九天

文章目录

    • 69. Sqrt(x)
    • 70. Climbing Stairs
    • 小结

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 exceededint 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}} 5 ​1​(( 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);

小结

今天刷题不知道怎么说了,感觉满满的挫败感啊,不过也确实补充了很多知识,现在感觉自己慢慢积攒的知识越来越多没有去细究了,希望以后能够在反复训练之中慢慢越来越熟练。

  • 牛顿迭代法
  • 二分查找
  • 动态规划
  • 斐波拉契数列

更多推荐

[日常刷题]LeetCode第九天

本文发布于:2024-02-11 14:15:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1681425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日常   第九天   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!