20190821算法题存档

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?

public class Solution {
    public int candy(int[] ratings) {
       int result = 0;
        int num = ratings.length;
        if(num ==  1) {
            return 1;
        }

        int[] tmp = new int[num];
        for(int i = 0; i < num; i++) {
            tmp[i] = 1;
        }
        for(int i = 1; i < num; i++) {
            if(ratings[i] > ratings[i - 1]) {
                tmp[i] = tmp[i - 1] + 1;
            }
        }
        for(int i = num - 1; i > 0; i--) {
             if(ratings[i - 1] > ratings[i] && tmp[i - 1] <= tmp[i]) {
                tmp[i - 1] = tmp[i] + 1;
            }
        }
        for(int i = 0; i < num; i++) {
            result += tmp[i];
        }
        return result;
    }
}

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.

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
       int start = gas.length - 1;
        int end = 0;
        int tmp = gas[start] - cost[start];
        while(start > end) {
            if(tmp >= 0){
                tmp += gas[end] - cost[end];
                ++end;
            }else{
                --start;
                tmp += gas[start] - cost[start];
            }
        }
        return tmp >= 0 ? start : -1;
    }
}

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#.

  1. First node is labeled as 0. Connect node 0 to both nodes1and2.
  2. Second node is labeled as1. Connect node1to node2.
  3. Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1↵      / ↵     /   ↵    0 --- 2↵         / ↵         \_/↵
import java.util.ArrayList;
import java.util.HashMap;
public class Solution {
    private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();

    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        return recurrence(node);
    }

    public UndirectedGraphNode recurrence(UndirectedGraphNode node) {
        if(node != null) {
            if (map.containsKey(node.label)) {
                return map.get(node.label);
            }
            UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
            map.put(clone.label, clone);
            for (UndirectedGraphNode neighbor : node.neighbors) {
                clone.neighbors.add(recurrence(neighbor));
            }
            return clone;
        }
        return null;
    }
}

Given a 2D board containing'X'and'O', capture all regions surrounded by'X'.

A region is captured by flipping all'O's into'X's in that surrounded region .

For example,

X X X X↵X O O X↵X X O X↵X O X X↵

After running your function, the board should be:

X X X X↵X X X X↵X X X X↵X O X X
public class Solution {
    public void solve(char[][] board) {
        if(board == null || board.length <= 0|| board[0].length <= 0){
            return;
        }
        int row = board.length;
        int col = board[0].length;

        for(int i = 0; i < col; i++){
            recurrence(board, 0, i, row, col);
            recurrence(board, row-1, i, row, col);
        }

        for(int i = 0; i < row; i++){
            recurrence(board, i, 0, row, col);
            recurrence(board, i, col-1, row, col);
        }

        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(board[i][j] == 'O'){
                    board[i][j] = 'X';
                } else if(board[i][j] == '!'){
                    board[i][j] = 'O';
                }
            }
        }
    }
    private void recurrence(char[][] board, int row, int col, int rowNum, int colNum) {
        if(board[row][col] == 'O'){
            board[row][col] = '!';
            if(row > 1){
                recurrence(board, row-1, col, rowNum, colNum);
            }
            if(col > 1){
                recurrence(board, row, col-1, rowNum, colNum);
            }
            if(row < rowNum -1){
                recurrence(board, row+1, col, rowNum, colNum);
            }
            if(col < colNum -1){
                recurrence(board, row, col+1, rowNum, colNum);
            }
        }
    }
}

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,

    1↵   / ↵  2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.

mport java.util.ArrayList;
public class Solution {
   private ArrayList<String> list = new ArrayList<>(); 
    
    public int sumNumbers(TreeNode root) {
        if(root == null) {
            return 0;
        }
        recurrence(root, "");
        int result = 0;
        for(String s : list) {
            result += Integer.valueOf(s);
        }
        return result;
    }
    
    private void recurrence(TreeNode node, String temp) {
         if(node != null) {
            temp += node.val;
            if(node.left == null && node.right == null) {
                list.add(temp);
            }
            recurrence(node.left, temp);
            recurrence(node.right, temp);
        }
    }
}

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.

Your algorithm should run in O(n) complexity.

import java.util.HashMap;
public class Solution {
     public int longestConsecutive(int[] num) {
        if (num == null || num.length == 0) {
            return 0;
        }
        if (num.length == 1) {
            return 1;
        }
        HashMap<Integer, Boolean> map = new HashMap<>();
        for (int i = 0; i < num.length; ++i) {
            map.put(num[i], true);
        }
        int temp = 1;
        int result = temp;
        for (int i = 0; i < num.length; ++i) {
            if (map.get(num[i])) {
                int pre = num[i] - 1;
                int post = num[i] + 1;
                while (map.containsKey(pre)) {
                    map.put(pre, false);
                    temp++;
                    pre--;
                }
                while (map.containsKey(post)) {
                    map.put(post, false);
                    temp++;
                    post++;
                }
                result = Math.max(temp, result);
                temp = 1;
            }
        }
        return result;
    }
}
发布了141 篇原创文章 · 获赞 19 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_40318210/article/details/100005797