Simulate the eating process described in the problem. In fact, because of the termination-condition check, the implementation is not that straightforward.
classSolution { public: intcountStudents(vector<int>& students, vector<int>& sandwiches){ constint n = students.size(); int ans = 0; queue<int> stu; for (int i : students) { stu.push(i); } stack<int> sand; for (int i = sandwiches.size() - 1; i >= 0; --i) { sand.push(sandwiches[i]); } while (!stu.empty()) { int current = stu.size(); while (!stu.empty()) { int s = stu.front(); stu.pop(); if (s == sand.top()) { sand.pop(); ++ans; break; } else { --current; stu.push(s); if (current == 0) { return n - ans; } } } } return0; } };
Time complexity: O(students.size() * sandwiches.size()), space complexity: O(students.size() + sandwiches.size()).
Actually my implementation made it too complicated. Since we need to traverse students anyway, the students’ order does not really matter. We can count the types students like, then continuously check whether the top of the sandwiches stack can be consumed.
1701. Average Waiting Time
Simulate the cooking process. For each customer, determine whether cooking can start immediately when they arrive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { using ll = longlong; public: doubleaverageWaitingTime(vector<vector<int>>& customers){ ll wait = 0; ll current = 0; for (constauto& v : customers) { if (current <= v[0]) { current = v[0] + v[1]; wait += v[1]; } else { wait += (current + v[1] - v[0]); current += v[1]; } } double n = customers.size(); return wait / n; } };
Time complexity: O(customers.size()), space complexity: O(1).
template <typename T> ostream& operator <<(ostream& out, const vector<T>& a) { out << "["; bool first = true; for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]"; return out; } classSolution { // 二分? 如何判定?N * log N // greedy, 向密的地方靠近 // 把1移到对应位置的花费是中间0的数目 // 遍历集合地点,然后左右找k个1. N * K // 右边取 x 个,左边取 k - x个 // 贪心, 左边右边谁近取谁 // 更新集合位置,双指针更新左右边界 public: intminMoves(vector<int>& nums, int k){ vector<int> ones; int zero = 0; for (int i : nums) { if (i == 1) { ones.push_back(zero); } else { ++zero; } } zero = 0; int one = 0; int left = 0, right = 0; int ans = 0; int currentAns = 0; // [left, right) for (; right < k; ++right) { currentAns += ones[right]; } ans = currentAns; for (int mid = 0; mid < nums.size(); ++mid) { if (nums[mid] == 0) { ++zero; currentAns -= right - one; // right currentAns += one - left; // left; } else { ++one; } while (right < ones.size() && ones[right] - zero <= zero - ones[left]) { currentAns += ones[right] - zero - (zero - ones[left]); ++right; ++left; } ans = min(ans, currentAns); } return ans; } };
Time complexity: O(N), space complexity: O(N).
During the contest, I spent half an hour debugging two bugs. I missed submission by one minute. Huge loss.