Problem
Write a function that, given an integer N (1 ≤ N ≤ 100), returns an array containing N unique integers that sum up to 0. The function can return any such array.
For example, given N = 4, the function could return [1, 0, −3, 2] or [−2, 1, −4, 5]. The answer [1, −1, 1, 3] would be incorrect (because value 1 occurs twice). For N = 3 one of the possible answers is [−1, 0, 1] (but there are many more correct answers).
Any ideas would be much appreciated.
Any better implementation?
or any holes in my answer?
Current implementation
public static int[] Solution(int N)
{
HashSet set = new HashSet();
int a = N % 2;
int b = N / 2;
for (int i = 0; i < b; i++)
{
if (!set.contains(b - i))
{
set.add(-(b - i));
}
}
if(a != 0)
{
set.add(0);
}
for (int i = 0; i < b; i++)
{
if (!set.contains(b - i))
{
set.add((b - i));
}
}
int[] entries = set.stream().mapToInt(Integer::intValue).toArray();
return entries;
}
a
andb
as you have done, then make the set or array (1, -1, 2, -2, ... b, -b) and insert 0 as well if a==1. No need to check if any numbers are already in the set, since it's clearly impossible that they are. Sorry, not offering code because I don't program in Java. It's about five lines of Python. \$\endgroup\$ – nigel222 2 days ago