Leetcode算法学习
油腻的老码
这个作者很懒,什么都没留下…
展开
-
Leetcode刷题:动态规划-爬楼梯
题目假设你正在爬楼梯。需要n阶你才能到达楼顶。每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?分析由题可以知道,爬楼梯一次可以爬1台阶或一次可以爬两台阶。我们使用枚举法可以知道,第一台阶有1种方法,爬两台阶有2两种方法,爬3台阶有3种方法,爬4台阶有5种方法...到这一步,想必大家已经看出一点端倪了吧,从第3台阶开始,所拥有的方法都是前面两台阶之和。按照这种规律就可以发现第n阶台阶就等于(n-1)台阶的方法数加上(n-2)台阶的方法数。知道了规律那就好办了..原创 2021-10-26 19:25:51 · 323 阅读 · 0 评论 -
Leetcode刷题:求斐波那契数列
分析该题可以考虑使用二分查找的方式来解答,解答代码如下代码public class Solutions{ public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left);//防止溢满 if (nu原创 2021-10-26 09:06:53 · 116 阅读 · 0 评论 -
Leetcode刷题:给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target , 写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
分析看到这题第一想到的就是二分查找。不用说了直接上代码代码public class dome { public static int result(int[] nums, int target) { //设定区间索引 int left = 0; int right = nums.length -1; while (left<=right) { int mid = left + (right - left) / 2;//防止溢满 if (nums[原创 2021-09-19 20:18:41 · 672 阅读 · 0 评论 -
Leetcode刷题:在一个排序数组中查找目标值,并找出它的位置的索引。 如果没有该值,则返回它要插入的位置的索引。
分析该题可以考虑使用二分查找的方式来解答,解答代码如下代码public class Solutions{ public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left);//防止溢满 if (nu原创 2021-09-19 20:10:47 · 240 阅读 · 1 评论 -
Leetcode刷题:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾, 同时保持非零元素的相对顺序。
分析这道题可以使用双指针的知识来解答,先遍历nums数组,然后判断不为0的元素,将不为0的元素用一个tmp来存储,再定义一个新指针用来存储下一个不为0的元素的索引,以此类推。具体代码如下。代码public class demo{ public int[] moveZeroes(int[] nums){ //如果输入的数组为空直接返回一个空数组 if(nums == null || nums.lengths == 0){ retu原创 2021-09-19 19:48:22 · 1397 阅读 · 0 评论