1. 程式人生 > >牛客網編程練習之編程馬拉松:數據庫連接池

牛客網編程練習之編程馬拉松:數據庫連接池

ranking system left amp ati util bar 題目 question

技術分享圖片

技術分享圖片

只需要兩個變量即可,一個維護著連接池的當前連接數,一個維護著連接池的最大連接數。

AC代碼:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author CC11001100
 */
public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		while (sc.hasNextLine()) {
			int n = sc.nextInt();
			sc.nextLine();
			List<String> operators = new ArrayList<>();
			while (n-- > 0) {
				operators.add(sc.nextLine());
			}
			System.out.println(resolve(operators));
		}

	}

	private static int resolve(List<String> operators) {
		int maxConnection = 0;
		int nowConnection = 0;
		for (String operator : operators) {
			if (operator.contains("disconnect")) {
				nowConnection++;
			} else if (operator.contains("connect")) {
				if (nowConnection <= 0) {
					maxConnection++;
				} else {
					nowConnection--;
				}
			}
		}
		return maxConnection;
	}

}

題目來源: https://www.nowcoder.com/practice/05f97d9b29944c018578d98d7f0ce56e?tpId=3&tqId=10884&tPage=1&rp=&ru=/ta/hackathon&qru=/ta/hackathon/question-ranking

牛客網編程練習之編程馬拉松:數據庫連接池