1304. Find N Unique Integers Sum up to Zero

Given an integer n, return any array containing n unique integers such that they add up to 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

Rust Solution

struct Solution;

impl Solution {
    fn sum_zero(n: i32) -> Vec<i32> {
        let n = n as usize;
        let mut res: Vec<i32> = vec![0; n];
        let mut sum: i32 = 0;
        for i in 0..n - 1 {
            sum -= i as i32;
            res[i] = i as i32;
        }
        res[n - 1] = sum;
        res
    }
}

#[test]
fn test() {
    let s: i32 = Solution::sum_zero(5).iter().sum();
    assert_eq!(s, 0);
    let s: i32 = Solution::sum_zero(3).iter().sum();
    assert_eq!(s, 0);
    let s: i32 = Solution::sum_zero(1).iter().sum();
    assert_eq!(s, 0);
}

Having problems with this solution? Click here to submit an issue on github.