???? 算法题 ???? |
---|
???? 算法题 ???? |
---|
给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。
请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
示例:
输入:nums = [4,3,2,7,8,2,3,1]
输出:[5,6]
示例 2:
输入:nums = [1,1]
输出:[2]
提示:
代码:
public class Solution {
public IList<int> FindDisappearedNumbers(int[] nums) {
int n = nums.Length;
for (int i = 0; i < nums.Length; i++)
{
int x = (nums[i] - 1)% n; //获取到原有的数值
nums[x] += n; //对重复出现的+n
}
List<int> res = new List<int>();
for (int i = 0; i < n; i++)
{
if (nums[i] <= n)
{
res.Add(i+1);
}
}
return res;
}
}
执行结果
通过
执行用时:92 ms,在所有 C# 提交中击败了58.36%用户
内存消耗:37.4 MB,在所有 C# 提交中击败了8.56%的用户
思路解析
代码:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
for (int num : nums) {
int x = (num - 1) % n;
nums[x] += n;
}
List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
ret.add(i + 1);
}
}
return ret;
}
}
执行结果
通过
执行用时:3 ms,在所有 Java 提交中击败了100.00%的用户
内存消耗:47.3 MB,在所有 Java 提交中击败了55.49%的用户
复杂度分析
时间复杂度:O( n )
空间复杂度:O( 1)
C#
和 Java
两种编程语言进行解题