LeetCode|LeetCode #1304 Find N Unique Integers Sum up to Zero 和为零的N个唯一整数
1304 Find N Unique Integers Sum up to Zero 和为零的N个唯一整数
【LeetCode|LeetCode #1304 Find N Unique Integers Sum up to Zero 和为零的N个唯一整数】Description:
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example:
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
题目描述:
给你一个整数 n,请你返回 任意 一个由 n 个 各不相同 的整数组成的数组,并且这 n 个数相加和为 0 。
示例 :
示例 1:
输入:n = 5
输出:[-7,-1,1,3,4]
解释:这些数组也是正确的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。
示例 2:
输入:n = 3
输出:[-1,0,1]
示例 3:
输入:n = 1
输出:[0]
提示:
1 <= n <= 1000
思路:
从 1 - n到 n - 1按照步长为 2加入到结果数组即可
时间复杂度O(n), 空间复杂度O(1)
代码:
C++:
class Solution
{
public:
vector sumZero(int n)
{
vector result(n);
for (int num = 1 - n, i = 0;
num < n;
num += 2, i++) result[i] = num;
return result;
}
};
Java:
class Solution {
public int[] sumZero(int n) {
int result[] = new int[n];
for (int i = 0, num = 1 - n;
i < n;
i++, num += 2) result[i] = num;
return result;
}
}
Python:
class Solution:
def sumZero(self, n: int) -> List[int]:
return range(1 - n, n, 2)
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 运行报错Cannot|运行报错Cannot find module '@babel/compat-data/corejs3-shipped-proposals’
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路