1304 .Find N Unique Integers Sum up to Zero LeetCode
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
🧠Logic Summary:
-
Use pairs like (1, -1), (2, -2) to balance the sum to 0.
-
For even
n
, just these pairs are enough. -
For odd
n
, you need an extra0
in the center to make it up ton
elements.
Input: n = 5
Output: [-2, -1, 0, 1, 2] // sum = 0
class Solution {
public int[] sumZero(int n) {
int num = 1; // Start from 1
int[] result = new int[n]; // Result array of size n
// Fill pairs like (1, -1), (2, -2), ...
for (int i = 0; i < n / 2; i++) {
result[i] = num; // Positive number
result[n - 1 - i] = -num; // Negative counterpart
num++; // Move to next number
}
// If n is odd, put a 0 in the middle (0 balances itself)
if (n % 2 != 0) {
result[n / 2] = 0;
}
// Return the array where the sum of all elements is zero
return result;
}
}
Comments
Post a Comment