LeetCode经典编程题(六)

1. candy

Description

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?

Solution
  1. Scan from left to right. Ensure candies[i+1] = candies[i] + 1, if ratings[i+1] > ratings[i].
  2. Scan from right to left. Similar to the step one. candies[i-1] = max (candies[i-1] , candies[i] + 1), if ratings[i-1] > ratings[i]
Code
public class Solution {
    public int candy(int[] ratings) {
        int[] candies = new int[ratings.length];
        for(int i = 0; i < candies.length; i++){
            candies[i] = 1;
        }
        for(int i = 1; i < ratings.length; i++){
            if(ratings[i]>ratings[i-1]){
                candies[i] = candies[i-1] + 1;
            }
        }
        int total = 0;
        for(int i = ratings.length-1; i>=1; i--){
            if(ratings[i-1]>ratings[i]){
                candies[i-1] = Math.max(candies[i-1], candies[i] + 1);
            }
            total += candies[i];
        }
        total+=candies[0];
        return total;
    }
}

2. gas-station

Description

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

Solution

<==> A list of numbers contains negative and positive numbers. We need to find a position so that if we add numbers from it, the sum will always be positive.

  1. sum < 0 , start - -
  2. sum >=0, next + +
Code
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = gas.length - 1;
        int next = 0;
        int sum = gas[start] - cost[start];
        while(next < start){
            if(sum < 0){
                start--;
                sum += gas[start] - cost[start];
            }else{
                sum += gas[next] - cost[next];
                next++;
            }
        }
        if(sum >= 0){
            return start;
        }else{
            return -1;
        }
    }
}

3. clone-graph

Description

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ’s undirected graph serialization:
Nodes are labeled uniquely.

We use#as a separator for each node, and,as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph{0,1,2# 1,2# 2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by#.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2(itself), thus forming a self-cycle.

Visually, the graph looks like the following:

   1
  / \
 /   \
0 --- 2
     / \
     \_/
Solution

Use a stack to save the node and its neighbors. When we push its neighbors, we need to guarantee this node has not be visited. Pop one node each time, and copy it.

Code
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
import java.util.*;
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null){
            return null;
        }
        ArrayList<Integer> exist = new ArrayList<>();
        Stack<UndirectedGraphNode> stack = new Stack<>();
        stack.push(node);
        exist.add(node.label);
        UndirectedGraphNode result = null;
        while(!stack.isEmpty()){
            UndirectedGraphNode gnode = stack.pop();
            UndirectedGraphNode n = new UndirectedGraphNode(gnode.label);
            n.neighbors = new ArrayList<UndirectedGraphNode>(gnode.neighbors);
            if(gnode == node) result = n;
            for(int i = 0; i < n.neighbors.size(); i++){
                if(!exist.contains(n.neighbors.get(i).label)){
                    exist.add(n.neighbors.get(i).label);
                    stack.push(n.neighbors.get(i));
                }
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LeetCode是一个著名的在线编程题库,可以帮助计算机程序员提升编程能力。LeetCode目涵盖了算法、数据结构、字符串、数组、链表等多个方面的知识,对于求职面试以及算法竞赛准备非常有帮助。 LeetCode上的编程题目分为简单、中等和困难三个难度级别。每个目都有详细的目描述、输入输出示例以及参考答案等内容。在解决每个问时,我们需要仔细阅读目,并根据目要求提供正确的解答。 通常,我们需要使用编程语言如Python、C++等来实现解思路。在编码之前,我们需要先分析问,并找到合适的算法或数据结构来解决问。一般来说,我们可以使用递归、迭代、动态规划等方法来解决常见的编程问。 在LeetCode上,我们可以提交解答,并测试解答是否通过了所有的测试用例。如果通过了所有的测试用例,我们就可以得到目的AC(Accepted)结果,并获得该目的通过证书。如果没有通过所有的测试用例,我们可以检查自己的解答,查找解答中的错误或者不完善之处,并进行修改和优化。 总之,LeetCode编程题是一个优秀的学习和练习编程的平台。通过解答LeetCode上的编程题目,我们可以提升自己的编程能力,并且培养解决问的思维方式。无论是求职面试还是算法竞赛,LeetCode编程题都是非常有帮助的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值