Link Search Menu Expand Document

1304. Find N Unique Integers Sum up to Zero

Solution Code

C#

public class Solution {
    public int[] SumZero(int n) {
        int[] answer = new int[n];
        int index = 0;
    
        if (n % 2 == 1)
            answer[index++] = 0;
        
        n /= 2;
        
        for (int i = 1; i <= n; i++) {
            answer[index++] = i;
            answer[index++] = -i;
        }
        
        return answer;
    }
}

C++

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

Java

class Solution {
    public int[] sumZero(int n) {
        int[] answer = new int[n];
        int index = 0;
    
        if (n % 2 == 1)
            answer[index++] = 0;
        
        n /= 2;
        
        for (int i = 1; i <= n; i++) {
            answer[index++] = i;
            answer[index++] = -i;
        }
        
        return answer;
    }
}

Python

class Solution(object):
    def sumZero(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        answer = [i for i in range(1, (n // 2) + 1)]
        answer += [-i for i in answer]

        return answer if (n % 2 == 0) else answer + [0]

Ruby

# @param {Integer} n
# @return {Integer[]}
def sum_zero(n)
    answer = []
    answer << 0 if (n % 2 == 1)
    n /= 2
    n.times { |i| answer << (i + 1) << -(i + 1) }
    answer
end

Resources


© 2023. All rights reserved.