Linked List Cycle

题意:

Given a linked list, determine if it has a cycle in it.

Follow up:
    Can you solve it without using extra space?

思路:

如何判断一个链表存在环?可以设置两个指针,一个快,一个慢,沿着链表走,在无环的情况下,快指针很快到达终点。如果存在环,那么,快指针就会陷入绕圈,而最后被慢指针追上。

代码:
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:bool hasCycle(ListNode *head) {/*初始都指向 head */ListNode *pfast = head,*pslow = head;do{/*快指针两倍速*/if(pfast != NULL) pfast = pfast->next;if(pfast != NULL) pfast = pfast->next;/*到达 null,无环 */if(pfast == NULL) return false;/*慢指针*/pslow = pslow->next;}while(pfast != pslow);return true;}
};

Best Time to Buy and Sell Stock

题意:

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.

思路:

只能买卖一次,所以要找一个最大差值的两天,但要注意低的那一天是在前面的。所以可以维护一个最小值和一个最大差值,从前往后走,如果比最小值小则更新,如果减最小值的差值大于之前的最大差值,则更新最大差值。

注意如果维护的是最大值和最小值,最后返回一个最大-最小的数,会是错的哦!

代码:
class Solution {
public:int maxProfit(vector<int> &prices) {int n = prices.size();if(n <= 1) return 0;int min_value = prices[0];int ans = 0;for(vector<int>::iterator it = prices.begin();it != prices.end();it++){/* 更新最小值 */if(*it < min_value){min_value = *it;}/* 更新最大差值 */if(*it - min_value > ans){ans = *it - min_value;}}return ans;}
};

Best Time to Buy and Sell Stock II

题意:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:

要求可以多次转手买卖股票所能得到的最大收益。那么,在所有的股票价格变动的序列里,我只要找出所有的上升序列,在每一段单调上升序列的开始买入股票,结束时卖出股票,就可以得到股票价格上升的利润。

那么,这些上升序列怎么求得呢?其实很简单,因为每一段上升序列都是由一个上涨的两天股票价格小区间组成,即是假如有 1 3 6 7 的上升序列,你只要看成  (1,3)、(3,6)、(6,7)的小序列构成,然后利润就是每个小区间的差值。简单说,就是只要遇到当前价格比前一天高,就加到总利润中去,最后的值就是所求答案。

代码:
class Solution {
public:int maxProfit(vector<int> &prices) {int ans = 0;int n = prices.size();for(int i = 1;i < n;++i){if(prices[i] > prices[i-1]){ans += prices[i]-prices[i-1];}}return ans;}
};

Unique Binary Search Trees

题意:

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1\       /     /      / \      \3     2     1      1   3      2/     /       \                 \2     1         2                 3
思路:

n = 0 时,空树,只有一棵。n = 1 时,只有一种可能,也是 1。

n >= 2 时,对 12....n,分别以 i 为根节点,那么左边有 i-1 个节点,右边有 n-i-1 个节点,所以

f[n] += f[k-1]*f[n-k-1], k = 1,2,....,n-1

代码:
class Solution {
public:int numTrees(int n) {int *cnt = new int[n+1];memset(cnt,0,(n+1)*sizeof(int));cnt[0] = 1;cnt[1] = 1;for(int i = 2;i <= n;i++)for(int j = 0;j < i;++j)cnt[i] += cnt[j]*cnt[i-j-1];int sum = cnt[n];delete []cnt;return sum;}
};

Populating Next Right Pointers in Each Node

题意:

Given a binary tree

    struct TreeLinkNode {TreeLinkNode *left;TreeLinkNode *right;TreeLinkNode *next;}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1/  \2    3/ \  / \4  5  6  7

After calling your function, the tree should look like:

         1 -> NULL/  \2 -> 3 -> NULL/ \  / \4->5->6->7 -> NULL
思路:

要为每个节点的 next 指针赋值,指向本层的右边节点,最右节点 next 指针为空。下面是两种解法。

代码:

解一:

/*** Definition for binary tree with next pointer.* struct TreeLinkNode {*  int val;*  TreeLinkNode *left, *right, *next;*  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}* };*/
#include<queue>class Solution {
public:void connect(TreeLinkNode *root) {/* 定义处理队列 */queue<TreeLinkNode*> q;if(root != NULL) q.push(root);while(!q.empty()){/* 临时队列,用于存储下一层节点 */queue<TreeLinkNode *> next;while(!q.empty()){TreeLinkNode* cur = q.front();q.pop();/* 修改 next 指针 */if(!q.empty()){TreeLinkNode* val = q.front();cur->next = val;}else cur->next = NULL;/* 添加下一层节点 */if(cur->left != NULL)next.push(cur->left);if(cur->right != NULL)next.push(cur->right);}/* 复制队列 */if(!next.empty())q = next;}}
};

解二:

/*** Definition for binary tree with next pointer.* struct TreeLinkNode {*  int val;*  TreeLinkNode *left, *right, *next;*  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}* };*/
class Solution {
public:void connect(TreeLinkNode *root) {/*节点为空,直接返回*/if (root==NULL) return;/*如果父节点有左节点和右节点,那么左节点的下一个是父节点的右节点*/if (root->left && root->right)root->left->next = root->right;/*如果父节点有右节点和 next 指针不空,则右节点指向父节点 next 节点的左节点 */if (root->next && root->right)root->right->next = root->next->left;/*左右孩子做连接*/connect(root->left);connect(root->right);}
};

【LeetCode】Algorithms 题集(二)相关推荐

  1. LeetCode简单题之二叉搜索树中的众数

    题目 给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素). 如果树中有不止一个众数,可以按 任意顺序 返回. 假定 BST 满足如 ...

  2. LeetCode简单题之二叉搜索树的最小绝对差/最小距离

    题目 给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 . 差值是一个正数,其数值等于两值之差的绝对值. 示例 1: 输入:root = [4,2,6,1,3] 输出: ...

  3. LeetCode简单题之二叉搜索树的范围和

    题目 给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和. 示例 1: 输入:root = [10,5,15,3,7,null,18], low = 7, ...

  4. LeetCode简单题之二叉搜索树中的搜索

    题目 给定二叉搜索树(BST)的根节点 root 和一个整数值 val. 你需要在 BST 中找到节点值等于 val 的节点. 返回以该节点为根的子树. 如果节点不存在,则返回 null . 示例 1 ...

  5. LeetCode中等题之二倍数对数组

    题目 给定一个长度为偶数的整数数组 arr,只有对 arr 进行重组后可以满足 "对于每个 0 <= i < len(arr) / 2,都有 arr[2 * i + 1] = 2 ...

  6. leetcode刷题集:栈与队列

    文章目录 01 用两个栈模拟一个队列 02 包含min函数的栈 03 栈的压入.弹出序列 队列的最大值 01 用两个栈模拟一个队列 用两个栈实现一个队列.队列的声明如下,请实现它的两个函数 appen ...

  7. leetcode算法题--不同的二叉搜索树

    原题链接:https://leetcode-cn.com/problems/unique-binary-search-trees/ 相关题目:leetcode算法题--不同的二叉搜索树 II 1.递归 ...

  8. C#LeetCode刷题-二叉搜索树

    二叉搜索树篇 # 题名 刷题 通过率 难度 220 存在重复元素 III 19.3% 中等 315 计算右侧小于当前元素的个数 31.9% 困难 327 区间和的个数 29.5% 困难 352 将数据 ...

  9. ​LeetCode刷题实战450:删除二叉搜索树中的节点

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

最新文章

  1. 2015年十佳IDC评选结果:50强名单揭晓
  2. 十大编程算法助程序员走上高手之路
  3. POJ3160强连通+spfa最长路(不错)
  4. ie8不兼容java项目_[Java教程]ie8以下不兼容document.getElementsByName解决方法
  5. 【杂谈】计算机视觉在人脸图像领域的十几个大的应用方向,你懂了几分?
  6. 设计模式のObserver Pattern(观察者模式)----行为模式
  7. 2020 CCPC网络赛 赛后感
  8. 单体、分布式、微服务、Serverless软件架构一览
  9. (68)信号发生器DDS协议(第14天)
  10. linux线程切换回调函数,linux C线程退出回调函数
  11. Struts学习笔记总结
  12. AS/400开发经验点滴(六)如何制作下拉菜单
  13. rancher 权限 添加用户_Kubernetes身份认证和授权操作全攻略:访问控制之Service Account...
  14. matlab主成分分析散点图_主成分分析与matlab
  15. LIN总线、CAN总线、FlexRay总线和MOST总线
  16. 前端推荐的书籍学习(必看)
  17. Git冲突解决: git checkout高级用法
  18. BGPv4-原理介绍+报文分析+配置示例
  19. U盘变成RAW格式怎么修复?U盘数据如何恢复?
  20. Axure的热区元件的作用

热门文章

  1. 高端蓝牙耳机哪个牌子好?四款高音质不错的蓝牙耳机推荐
  2. linux中su 与su-的区别
  3. pygame 精灵精灵组
  4. python判断是否为整数的函数_实现函数 isInteger(x) 来判断 x 是否是整数
  5. UD三分区补充教程1——激活不同分区对于UD三分区bios启动和uefi启动兼容性影响的讨论
  6. 机器学习项目一:共享单车
  7. Uninstall tool 3.6.0 授权版
  8. 英语单词常见词根总结
  9. 在EXCEL表格中如何快速换行
  10. Mass Assignment 防止Hacked