[LeetCode] Find N Unique Integers Sum up to Zero

준규·2023년 1월 13일
0

1.문제


Given an integer n, return any array containing n unique integers such that they add up to 0.


정수 n이 주어질 때 n개의 중복되지 않는 숫자를 가지고 모든 숫자들의 합이 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]

Constraints:

1 <= n <= 1000


2.풀이

  1. n의 절반 만큼 +- i를 넣어준다. (반복문을 돌면서 i 증가)
  2. n이 홀수라면 0을 추가해준다.

/**
 * @param {number} n
 * @return {number[]}
 */
const sumZero = function (n) {
  const result = [];
  const mid = n / 2;

  // n의 절반 만큼 +- i 값을 result에 넣는다
  for (let i = 1; i <= mid; i++) {
    result.push(i);
    result.push(-i);
  }

  // 만약 n이 홀수라면 0을 추가로 넣어주고 리턴한다.
  if (n % 2 !== 0) result.push(0);

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글