8 questions. Covers Product except self.
Questions 1 to 5 of 8
cpp #include <cstddef> #include <iostream> #include <utility> #include <vector> using namespace std; void sort_flags(vector<int>& a) { size_t lo = 0, mid = 0, hi = a.size(); while (mid < hi) { if (a[mid] == 0) { swap(a[lo], a[mid]); ++lo; ++mid; } else if (a[mid] == 1) { ++mid; } else { --hi; swap(a[mid], a[hi]); } } } int main() { vector<int> v = {2, 1, 0, 2, 1}; sort_flags(v); for (int x : v) cout << x << ' '; }
productExceptSelf
Use the arrows to put the steps in order.
running
result[i]
nums[i]
result[i - 1]
nums[i - 1]
result
nums
int
mid
sort_flags
hi
cpp #include <iostream> #include <vector> using namespace std; vector<long long> productExceptSelf(const vector<int>& nums) { size_t n = nums.size(); vector<long long> result(n, 1); long long running = 1; for (size_t i = 0; i < n; ++i) { result[i] = running; running *= nums[i]; } running = 1; for (size_t i = n; i > 0; --i) { result[i - 1] *= running; running *= nums[i - 1]; } return result; } int main() { for (long long x : productExceptSelf({2, 5, -1, 3})) cout << x << ' '; }
3 question(s) left on this page.