Cover image for LeetCode Daily Problem P2197 Replace Non-Coprime Numbers in Array

LeetCode Daily Problem P2197 Replace Non-Coprime Numbers in Array

Words 225
Views
Visitors

Timeline

Timeline

2025-09-16

init

lcm least common multiple, gcd greatest common divisor, stack

Problem:

<numeric>contains std::lcm and std::gcd, used to calculate the least common multiple and greatest common divisor respectively

12345678910111213141516171819202122232425262728293031
#include <numeric>#include <vector>using std::vector;class Solution {    public:        vector<int> replaceNonCoprimes(vector<int> &nums)        {                int n = nums.size();                // Use nums[0..top] as a "stack"                int top = 0;                for (int i = 1; i < n; i++) {                        // std::gcd greatest common divisor                        // If the top of stack nums[top] and current nums[i] are not coprime, merge them.                        // A number may be non-coprime with multiple preceding numbers in a row.                        // So we must keep merging backward until it is coprime with the top of the stack.                        while (top >= 0 and std::gcd(nums[top], nums[i]) > 1) {                                // std::lcm least common multiple                                nums[i] = std::lcm(nums[top], nums[i]);                                // Pop the stack top and continue comparing with the new stack top                                top--;                        }                        // Push the merged result back onto the stack top                        nums[++top] = nums[i];                }                nums.resize(top + 1);                return nums;        }};
Loading comments…