1304. Find N Unique Integers Sum up to Zero #2144
-
|
Topics: Given an integer Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to generate an array of Approach
Let's implement this solution in PHP: 1304. Find N Unique Integers Sum up to Zero <?php
/**
* @param Integer $n
* @return Integer[]
*/
function sumZero($n) {
$result = [];
if ($n % 2 != 0) {
$result[] = 0;
$n--;
}
for ($i = 1; $i <= $n / 2; $i++) {
$result[] = $i;
$result[] = -$i;
}
return $result;
}
// Test cases
print_r(sumZero(5)); // Example output: [1, -1, 2, -2, 0]
print_r(sumZero(3)); // Example output: [1, -1, 0]
print_r(sumZero(1)); // Example output: [0]
?>Explanation:
This approach efficiently generates the required array by leveraging symmetric pairs of integers and zero, ensuring correctness and simplicity. The time complexity is O(n), as we iterate through each element once, and the space complexity is O(n) to store the result array. |
Beta Was this translation helpful? Give feedback.
We need to generate an array of
nunique integers such that their sum is zero. The solution involves creating pairs of positive and negative integers that cancel each other out. Ifnis odd, we include zero to ensure the sum remains zero.Approach
n: Ifnis odd, we include zero in the result array. This is because zero does not affect the sum and helps in making the total number of elements odd.nwas odd, we now haven-1elements left), we generate pairs of positive and negative integers. For each integerifrom1ton/2, we addiand-ito the result array. These pairs sum to zero, ensuring the overall sum of …