【LeetCode】Algorithms 题集(二)

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);

    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值