LeetCode经典编程题(六)

本文探讨了两个经典算法问题:糖果分配和环路加油站问题。糖果分配问题中,孩子们根据评分获得不同数量的糖果,目标是最小化总糖果数;环路加油站问题则是寻找一个起点,使得汽车在无限油箱条件下能完成一圈旅程。文章提供了详细的解决方案和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值