
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find N Unique Integers that Sum up to Zero in C++
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 −
- take an array A as final answer, and take x := 0
- for i in range 0 to n – 2
- A[i] = (i + 1)
- x := x + i + 1
- A[n – 1] = x
- return A
Example
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)) ; }
Input
10
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, -45, ]
Advertisements