442. Find All Duplicates in an Array(C++)
来源:互联网 发布:混沌战域神兵进阶数据 编辑:程序博客网 时间:2024/06/11 14:19
原題
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]
解題思路
題目限制了不能使用額外的空間以後時間複雜度為O(n),所以不可以用額外的空間來記錄數字出現的次數以後用排序來確定次數。但是這題有一個特別的條件,就是數組裏的數字的最大值不會大於數組的容量,以及沒有負數以及零的出現。所以我們可以通過修改數組本身來記錄數字的出現次數。例如a[0]的絕對值為4,它就會把a[4-1]的值取負。這樣若再有一個值為4,會發現a[4-1]的值為負,這表明了前面已經有一個4的存在,我們就可以得知有兩個4。
代碼
#include <cmath>
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> result;
if (nums.empty()) {
return result;
}
for (int i = 0; i < nums.size(); i++) {
int temp = abs(nums[i]) - 1;
if (nums[temp] < 0) {
result.push_back(temp+1);
}
else {
nums[temp] = -nums[temp];
}
}
return result;
}
};
感想
其實我沒想出來怎麼做才能符合條件,這個是我看了別人的寫法學會的。
- 442. Find All Duplicates in an Array (C++)
- 442. Find All Duplicates in an Array(C++)
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array**
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- 442. Find All Duplicates in an Array
- ESET NOD32 v11.0.154
- Java面向对象(2)
- 策略模式
- 第9章--模板
- python爬虫基础知识(二)--正则表达式
- 442. Find All Duplicates in an Array(C++)
- 什么时候使用assert
- CSS3(十八)
- Java中Lambda表达式的使用
- XAMPP设置MySql服务器用户名密码及远程访问权限
- 众所周知,在每一个彗星后都有一只UFO。这些UFO时常来收集地球上的忠诚支持者。不幸的是,他们的飞碟每次出行都只能带上一组支持者。因此,他们要用一种聪明的方案让这些小组提前知道谁会被彗星带走。他们为
- SQL优化
- Servlet实现文件下载
- Linux系统之网卡安装系统pxelinux