Wednesday, March 10, 2021

Leetcode Everyday: 1304. Find N Unique Integers Sum up to Zero. Easy

public class Solution {
    public int[] SumZero(int n) {
        var list = new int[n];
         
        var ndx = 0;
        for (var i = 1; i <= n / 2; ++i) {
            list[ndx++] = i;
            list[ndx++] = -i;
        }
         
        if (n % 2 == 1) {
            list[ndx] = 0;
        }
         
        return list;
    }
}
Alternative:
public class Solution {
    public int[] SumZero(int n) {
        var list = new int[n];
         
        for (int i = 1, ndx = 0; i <= n / 2; ++i, ndx += 2) {
            list[ndx] = i;
            list[ndx+1] = -i;
        }
         
        if (n % 2 == 1) {
            list[^1] = 0;
        }
         
        return list;
    }
}
This works, but is confusing:
public class Solution {
    public int[] SumZero(int n) {
        var list = new int[n];
         
        var i = 0;
        while (i < n / 2) {
            list[i++] = i;
            list[^i] = -i;
        }
          
        if (n % 2 == 1) {
            list[i] = 0;
        }
          
        return list;
    }
}
Source: https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/submissions/

No comments:

Post a Comment