2023-12-02 LeetCode每日一题(拼车)

2023-12-02每日一题

一、题目编号

1094. 拼车

二、题目链接

点击跳转到题目位置

三、题目描述

车上最初有 capacity 个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向

给定整数 capacity 和一个数组 trips , trip[i] = [numPassengersi, fromi, toi] 表示第 i 次旅行有 numPassengersi 乘客,接他们和放他们的位置分别是 fromi 和 toi 。这些位置是从汽车的初始位置向东的公里数。

当且仅当你可以在所有给定的行程中接送所有乘客时,返回 true,否则请返回 false。

示例 1:
在这里插入图片描述

示例 2:
在这里插入图片描述
提示:

  • 1 <= trips.length <= 1000
  • trips[i].length == 3
  • 1 <= numPassengersi <= 100
  • 0 <= fromi < toi <= 1000
  • 1 <= capacity <= 105

四、解题代码

class Solution {
public:bool carPooling(vector<vector<int>>& trips, int capacity) {int n = trips.size();int dp[1005];memset(dp, 0, sizeof(dp));for(int i = 0; i < n; ++i){int from = trips[i][1];int to = trips[i][2];int numPassengers = trips[i][0];dp[from] += numPassengers;dp[to] -= numPassengers;}for(int i = 0; i <= 1000; ++i){if(i > 0){dp[i] += dp[i-1];}if(dp[i] > capacity){return false;}}return true;}
};

五、解题思路

(1) 运用差分数组即可。