본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1304. Find N Unique Integers Sum up to Zero

반응형

https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

📕 풀이방법

📔 입력 및 초기화

정답 vector ans를 선언해줍니다.

📔 풀이과정

고유한 숫자에 부호만 나누어 ans에 분배해주면 됩니다. 짝수인 경우 부호만 다르게 고루 분배하면 되지만 n이 홀수라면 0을 포함해야 합니다.

1. -(n/2) ~ n/2까지의 범위로 loop를 수행하며 ans에 원소를 넣어줍니다.

2. loop탈출 후 n이 홀수라면 ans에 0을 넣어줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> sumZero(int n) {
        vector <int> ans;
        for(int i = -(n/2); i <= n/2; i++) {
            if(i == 0) continue;
            ans.push_back(i);
        }
        if(n % 2) ans.push_back(0);
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.