Problem Description
In this problem, you are given an integer n
where 1 <= n
<= 1000. Your task is to return an integer array containing n
distinct integers such that the summation of all the integers in the array is equivalent to 0
.
Solution Description
What are you going to return when n = 1
?
Surely, an array containing the integer 0
.
What about when n = 2
?
Now, you can pick any integer x
and its opposite -x
as the array elements since their summation will result in 0, for example, you can pick 1
and -1
. Note that, x
≠ 0
.
So, you can come up with 2 cases:
-
n is even
This is pretty simple. All you need to do is pickn / 2
unique integers and fill up the array with these integers and their corresponding opposites. -
n is odd
If you just pick0
as one of the array elements, there remains an even number of slots to be filled up. You can then just follow the logic for the case n is even.
Solution Code
If you are stuck with the solution of this problem, check the codes below:
C++
class Solution {
public:
vector<int> sumZero(int n) {
vector<int> answer;
if (n % 2 == 1)
answer.push_back(0);
n /= 2;
for (int i = 1; i <= n; i++) {
answer.push_back(i);
answer.push_back(-i);
}
return answer;
}
};
Java
class Solution {
public int[] sumZero(int n) {
int[] answer = new int[n];
int index = 0;
if (n % 2 == 1)
answer[index++] = 0;
n /= 2;
for (int i = 1; i <= n; i++) {
answer[index++] = i;
answer[index++] = -i;
}
return answer;
}
}
Python
class Solution(object):
def sumZero(self, n):
"""
:type n: int
:rtype: List[int]
"""
answer = [i for i in range(1, (n // 2) + 1)]
answer += [-i for i in answer]
return answer if (n % 2 == 0) else answer + [0]
C#
public class Solution {
public int[] SumZero(int n) {
int[] answer = new int[n];
int index = 0;
if (n % 2 == 1)
answer[index++] = 0;
n /= 2;
for (int i = 1; i <= n; i++) {
answer[index++] = i;
answer[index++] = -i;
}
return answer;
}
}
Ruby
# @param {Integer} n
# @return {Integer[]}
def sum_zero(n)
answer = []
answer << 0 if (n % 2 == 1)
n /= 2
n.times { |i| answer << (i + 1) << -(i + 1) }
answer
end