Suppose we have an integer n. We have to return any array that contains n unique integers, such that they add up to 0. So if input is n = 5, then one possible output will be [-7, -1, 1, 3, 4]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> sumZero(int n) { vector <int> ans(n); int x = 0; for(int i = 0; i < n - 1; i++){ ans[i] = (i + 1); x += (i + 1); } ans[n - 1] = -x; return ans; } }; main(){ Solution ob; print_vector(ob.sumZero(10)) ; }
10
[1, 2, 3, 4, 5, 6, 7, 8, 9, -45, ]