LeetCode - 442 - Find All Duplicates in an Array
2017-07-11 11:05
573 查看
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
自己的思路是用异或写,从头开始异或,异或到为0时说明出现过,然后发现大大的bug23333(1,2,3异或为0,尴尬)
后来发现漏了一个重要的条件,
1 ≤ a[i] ≤ n (n =
size of array), 嗯。。。
如果不卡空间的话,用unordered_map倒也是不错的选择
关于正解,a[i]的范围真的是很巧妙,正解看起来超优雅的哎。
一直做交换,复杂度最多也只会到2*n,常数不大,基本还是O(n)的复杂度
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
自己的思路是用异或写,从头开始异或,异或到为0时说明出现过,然后发现大大的bug23333(1,2,3异或为0,尴尬)
后来发现漏了一个重要的条件,
1 ≤ a[i] ≤ n (n =
size of array), 嗯。。。
如果不卡空间的话,用unordered_map倒也是不错的选择
关于正解,a[i]的范围真的是很巧妙,正解看起来超优雅的哎。
一直做交换,复杂度最多也只会到2*n,常数不大,基本还是O(n)的复杂度
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> ans; for (int i = 0; i < nums.size(); ) { if (nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]); else i++; } for (int i = 0; i < nums.size(); ++i) { if (nums[i] != i + 1) ans.push_back(nums[i]); } return ans; } };
相关文章推荐
- leetcode442 Find All Duplicates in an Array
- [leetcode 442] Find All Duplicates in an Array
- LeetCode-442-Find All Duplicates in an Array-M
- [C语言][LeetCode][442]Find All Duplicates in an Array
- leetcode 442 Find All Duplicates in an Array C++
- Find All Duplicates in an Array,leetcode,442
- LeetCode 442 Find All Duplicates in an Array
- leetcode442 Find All Duplicates In An Array Java
- [LeetCode]442 Find All Duplicates in an Array
- 【LeetCode-442】Find All Duplicates in an Array(C++)(
- Leetcode 442-Find All Duplicates in an Array
- LeetCode 442 --- Find All Duplicates in an Array
- [Leetcode] Find All Duplicates in an Array
- LeetCode: Find All Duplicates in an Array
- LeetCode-Find All Duplicates in an Array & Find All Numbers Disappeared in an Array
- leetcode之Find All Duplicates in an Array 问题
- Leetcode: Find All Duplicates in an Array
- LeetCode刷题【Array】 Find All Duplicates in an Array
- leetcode---442---FindAllDuplicatesinanArray
- LeetCode Find All Duplicates in an Array