Monday, March 16, 2020

LeetCode 1304. Find N Unique Integers Sum up to Zero

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

I am working my way to harder questions. These easy questions are indeed quite easy, although I almost make mistakes on the first run. The mistake was with the range indexing. For even numbers, I will need to use i+1 instead of i. However, the idea for the solution to these easy questions is quite easy to come by indeed.



class Solution(object):
    def sumZero(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        ans = []
        if n % 2 == 0:
            for i in range(n//2):
                ans.append(i+1)
                ans.append(-(i+1))
        else:
            for i in range(1, n//2+1):
                ans.append(i)
                ans.append(-i)
            ans.append(0)
        return ans

No comments:

Post a Comment