当前位置: 代码迷 >> 综合 >> Leetcode 1094 Car Pooling
  详细解决方案

Leetcode 1094 Car Pooling

热度:12   发布时间:2024-02-21 03:28:57.0

Leetcode 1094 Car Pooling

  • 题目
  • 代码

题目

You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)

Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.

Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true

Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true

Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true

代码

是一个要求最大重合数的问题。
考虑用一个数组,遍历位置区间,加上乘客数,最后遍历取出数组中的最大值和capacity比较。

class Solution {
    public boolean carPooling(int[][] trips, int capacity) {
    int[] num = new int[1001];for (int i = 0; i < trips.length; i++) {
    for (int j = trips[i][1]; j < trips[i][2]; j++) {
    num[j] += trips[i][0];}}int max = 0;for (int i = 0; i < num.length; i++) {
    max = Math.max(max, num[i]);}return max <= capacity;}
}

其实不需要记录下每个点的值,只需要记录每个发生变化的位置,在左端点位置加上乘客数,到右端点减去。最后遍历数组动态的计算当前的乘客数,如果已经超过了就提前结束。和上面的代码对比少了j的循环,runtime表现更好。

class Solution {
    public boolean carPooling(int[][] trips, int capacity) {
    int[] num = new int[1001];for (int[] trip : trips) {
    num[trip[1]] += trip[0];num[trip[2]] -= trip[0];}int max = 0;for (int i = 0; i < num.length; i++) {
    max += num[i];if (max > capacity) return false; // current capacity required}return true;}
}