[LeetCode] Find All Numbers Disappeared in an Array
2017-02-16 21:33
501 查看
题目链接在此
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
要求不用额外的空间,以及O(n)的时间。
额,这要求有点高啊。
不过有一个很重要的限制条件:1 ≤ a[i] ≤ n
于是大体思想就是:把数组中的每一个数(设为x),当做数组下标,把下标x处的数a[x]用其相反数-a[x]来代替。(当然,x要做下-1的处理,不然数组会越界)。
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
要求不用额外的空间,以及O(n)的时间。
额,这要求有点高啊。
不过有一个很重要的限制条件:1 ≤ a[i] ≤ n
于是大体思想就是:把数组中的每一个数(设为x),当做数组下标,把下标x处的数a[x]用其相反数-a[x]来代替。(当然,x要做下-1的处理,不然数组会越界)。
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> ans; for (int n : nums) { int val = abs(n) - 1; if(nums[val] > 0) nums[val] = -nums[val]; } for (int i = 0; i < nums.size(); i++) if (nums[i] > 0) ans.push_back(i + 1); return ans; } };
相关文章推荐
- [LeetCode]Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- leetcode ---448---FindAllNumbersDisappearedinanArray
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- 【LeetCode-448】 Find All Numbers Disappeared in an Array(C++)
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- [LeetCode]Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- [Leetcode] Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- [LeetCode]Find All Numbers Disappeared in an Array(Java)
- LeetCode No.448 Find All Numbers Disappeared in an Array
- leetcode-448- Find All Numbers Disappeared in an Array
- Leetcode 448 Find All Numbers Disappeared in an Array
- leetcode 448 Find All Numbers Disappeared in an Array C++
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- leetcode: Find All Numbers Disappeared in an Array
- Leetcode: Find All Numbers Disappeared in an Array
- [LeetCode] Find All Numbers Disappeared in an Array 找出数组中所有消失的数字