Leetcode - find-pivot-index
Leetcode - The K Weakest Rows in a Matrix

Leetcode - find-n-unique-integers-sum-up-to-zero

violet posted @ Feb 26, 2020 05:50:25 AM in 算法 with tags array Algorithm Golang 算法 , 378 阅读

https://leetcode.com/problems/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].

The example is very misleading. The very solution can be done just by giving [1, 2, 3, 4,..., sum - prevSum]. The only requirement is unique and summed up to 0.

func sumZero(n int) []int {
    result := make([]int, n)
    sum := 0
    for i := 0; i < n-1; i++ {
        result[i] = i+1
        sum += i+1
    }
    result[n-1] = 0-sum
    
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter