首页 > 代码库 > 数据结构与算法---leetcode部分

数据结构与算法---leetcode部分

               

 ----------------------个人作业,如果有后辈的作业习题一致,可以参考学习,一起交流,请勿直接copy

1.   Remove Nth Node From End of List(#19)

 

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note: Given n will always be valid. Try to do this in one pass.

 技术分享

·特殊情况判断à查找节点求得链表长度à删除节点(删除时做是否为末位的判断)-------链表要删除的节点数为:from the end of list and return its head。

2.   Merge Two Sorted Lists(#21)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 技术分享

·特殊情况判断à普通的merge排序结合链表的操作

3.   Search Insert Position(#35)

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples.

 

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

 

技术分享

·数组的查找判断

4.   Climbing Stairs(#70)

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?

 技术分享

·采用动态规划。第 n 步只与第 n - 1 步和 第 n - 2 步有关,即steps[n] = steps[n - 1] + steps[n - 2],用二元的数组来存储与第n步相关的前两步。

5.   Same Tree(#100)

Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

 技术分享

·分治递归,特殊情况判断(是否非空/元素个数一致)à判断当前节点和左右子树,遍历节点

6.   Best Time to Buy and Sell Stock(#121)

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

Example 1:

 

Input: [7, 1, 5, 3, 6, 4]
Output: 5
 
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

 

Input: [7, 6, 4, 3, 1]
Output: 0
 
In this case, no transaction is done, i.e. max profit = 0.

 技术分享

·贪心问题,先判断是否为空,空则错误退出。如果输入正确,则逐个比较,若当前结果较优,则替换较优解。其中i用来指向所遍历过的元素中最小值,j则用来遍历数组,两者作为下标所示数值相减即为当时的profit,如果此时的profit大于max,则替换max(即贪心),当j指向的值小于i指向的元素时,将i = j,继续循环。

 

数据结构与算法---leetcode部分