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; } };
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; } };