[LeetCode] 442. Find All Duplicates in an Array
来源:互联网 发布:网络短信平台免费 编辑:程序博客网 时间:2024/06/10 09:10
题目链接: https://leetcode.com/problems/find-all-duplicates-in-an-array/description/
Description
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:
Input:[4,3,2,7,8,2,3,1]Output:[2,3]
解题思路
题意为找出数组中出现两次的元素,有两种思路。
1. 对应位置取负数
因为数组大小为 n
,每个元素 nums[i]
都在 [1, n]
范围内,因此可以让每个下标对应范围内的一个数,由于下标从 0
开始,所以下标 i
对应数字 i + 1
。
遍历数组的每个元素 nums[i]
,检查 nums[abs(nums[i]) - 1]
,若为正数,则第一次遇到值为 nums[i]
的元素,将下标为 abs(nums[i]) - 1
的元素取负数,用以表示已经有了 nums[i]
这个数;若为负数,则表示之前已经有值为 abs(nums[i])
的元素,将该值添加到返回数组。
2. 交换元素至正确位置
遍历数组的每个元素 nums[i]
,将 nums[i]
与其正确位置的数 nums[nums[i] - 1]
交换,直至 nums[i] == nums[nums[i] - 1]
。此时要么 i == nums[i] - 1
,为同一个元素;要么 i != nums[i] - 1
,为两个相同值的不同元素,暂时不添加到返回数组,要不可能会出现重复。
待第一次遍历完后,进行第二次遍历,将与位置不对应的数添加到返回数组中,即为结果。
Code
1. 对应位置取负数
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; for (int i = 0; i < nums.size(); ++i) { if (nums[abs(nums[i]) - 1] < 0) { res.push_back(abs(nums[i])); } else { nums[abs(nums[i]) - 1] *= -1; } } return res; }};
2. 交换元素至正确位置
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; for (int i = 0; i < nums.size(); ++i) { while (nums[i] != nums[nums[i] - 1]) { int tmp = nums[nums[i] - 1]; nums[nums[i] - 1] = nums[i]; nums[i] = tmp; } } for (int i = 0; i < nums.size(); ++i) { if (i + 1 != nums[i]) res.push_back(nums[i]); } return res; }};
- [LeetCode]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
- leetCode-Find All Duplicates in an Array
- [leetcode] 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- leetcode:442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array(LeetCode)
- <leetcode>442. Find All Duplicates in an Array
- [leetcode]442. Find All Duplicates in an Array(java)
- [LeetCode]442. Find All Duplicates in an Array
- Leetcode 442. Find All Duplicates in an Array
- LeetCode笔记:442. Find All Duplicates in an Array
- 【LeetCode】 442. Find All Duplicates in an Array
- [leetcode]442. Find All Duplicates in an Array
- Leetcode 442. Find All Duplicates in an Array
- LeetCode 442. Find All Duplicates in an Array
- 详解mpstat、iostat、sar、vmstat命令的使用
- Ubuntu16.04.3 virtualbox IP地址配置IP地址 使虚拟机与宿主机ping通
- PLSQL设置显示的字符集及PLSQL的一些自身设置
- 练习:验证歌德巴赫猜想
- 公式编辑器小技巧
- [LeetCode] 442. Find All Duplicates in an Array
- 51nod 1488 帕斯卡小三角
- 为何F8是灰色的?单步调试不了呀? code blocks里面 build options是灰色一直点不了。 有编译器/// 在用codeblocks反编译的时候可能会遇到这样的问题。
- Oracle 12c安装教程
- 习题4(1)
- H5-表格的基本样式
- <<优先级低于+啊
- 模拟实现库函数strlen
- okhttp