LeetCode | 448. Find All Numbers Disappeared in an Array 数组技巧题
2018-02-04 15:29
197 查看
Givenan array of integers where 1 ≤ a[i] ≤ n (n =
size of array), some elements appear twice and othersappear once.
Findall the elements of [1, n] inclusive that do not appear inthis array.
Couldyou do it without extra space and in O(n) runtime? You may assume thereturned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
这一题和hard的第41题是一模一样的在我的博客里面也有,使用的方法也是一样的,保证能在O(n)的时间内计算出结果,
技巧就是使用nums[i]=0表示数字i+1出现过,之后只需要遍历一遍nums数组就能够得到哪几个数字是没有出现过的
size of array), some elements appear twice and othersappear once.
Findall the elements of [1, n] inclusive that do not appear inthis array.
Couldyou do it without extra space and in O(n) runtime? You may assume thereturned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
这一题和hard的第41题是一模一样的在我的博客里面也有,使用的方法也是一样的,保证能在O(n)的时间内计算出结果,
技巧就是使用nums[i]=0表示数字i+1出现过,之后只需要遍历一遍nums数组就能够得到哪几个数字是没有出现过的
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> result; int tmp,l; for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) continue; tmp = nums[i]; while (nums[tmp - 1] != 0) { l = tmp; tmp = nums[l - 1]; nums[l - 1] = 0; } } for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) result.push_back(i+1); } return result; } };
相关文章推荐
- Longest Increasing Subsequence(最长增长子数列)-LeetCode关于数组的思路和技巧
- leetcode数组遍历技巧
- 【神奇的技巧】leetcode - 661. Image Smoother【整数位信息使用 + 二维数组边界考虑 + 数组的巧妙使用】
- leetCode 189. Rotate Array 数组
- Leetcode27:Remove Element(移除数组中指定的元素)
- LeetCode 14. Longest Common Prefix 找字符串数组最长相同前缀
- leetcode题解:Search for a Range (已排序数组范围查找)
- LeetCode—Merge Sorted Array两个有序数组排序
- PHP数组操作汇总 php数组的使用技巧
- leetcode 26 80 删除已排序数组中重复的数据
- 分拆数组技巧应用
- [LeetCode] Patching Array 补丁数组
- leetcode_453. Minimum Moves to Equal Array Elements 移动最小步数使数组中各数字相等
- [leetcode 59] Spiral Matrix II--------数组转圈赋值
- 递归-数组的子集:leetcode 78 Subsets
- linux shell 数组建立及使用技巧
- Yii基于数组和对象的Model查询技巧实例详解
- LeetCode问题53:最大的连续子数组和
- LeetCode 189 Rotate Array(旋转数组)
- leetcode:Rotate Array旋转数组