LeetCode刷题(78)~找到所有数组中消失的数字【原值作索引】
【摘要】 题目描述
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
...
题目描述
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
- 1
- 2
- 3
- 4
- 5
解答 By 海轰
提交代码(哈希)
vector<int> findDisappearedNumbers(vector<int>& nums) { unordered_map<int,int> m; vector<int> res; for(int num:nums) ++m[num]; for(int i=1;i<=nums.size();++i) { if(m.find(i)==m.end()) res.push_back(i); } return res; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
运行结果
提交代码(原地反转)
vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> res; for(int i=0;i<nums.size();++i) { int newindex=abs(nums[i])-1; if(nums[newindex]>0) nums[newindex]*=-1; } for(int i=1;i<=nums.size();++i) { if(nums[i-1]>0) res.push_back(i); } return res; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
运行结果
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
文章来源: haihong.blog.csdn.net,作者:海轰Pro,版权归原作者所有,如需转载,请联系作者。
原文链接:haihong.blog.csdn.net/article/details/108126770
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)