leetcode编程记录15 #442 Find All Duplicates in an Array
来源:互联网 发布:怎样经营淘宝网店 编辑:程序博客网 时间:2024/06/05 19:38
leetcode编程记录15 #442 Find All Duplicates in an Array
标签(空格分隔): leetcode
这次是一道比较简答的题目,但很有技巧性的一道题目,主要是要我们能够充分的利用题目的条件和所给的存储空间。题目如下:
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)的时间里面完成重复元素的记录,乍一看是不太可能的事情,但是我们要注意题目的条件,它所给出的每个数组中的元素的大小都是不超过数组索引的大小,那么我们显然就可以利用数组元素的这个信息来访问对应索引的数组元素,但是怎样才能知道数组元素中所存放的这个数有没有重复过呢?我们可以将根据数组元素索引到的数组元素的前一位设为负数,然后通过检查这一位的元素是否是负数来判断是否重复。
代码如下:
class Solution {public: vector<int> findDuplicates(vector<int>& nums) { vector<int> result; for (int i = 0; i < nums.size(); ++i) { int lastI = abs(nums[i]) - 1; if (nums[lastI] < 0) {result.push_back(abs(nums[i]));} nums[lastI] = -nums[lastI]; } return result; }};
阅读全文
0 0
- leetcode编程记录15 #442 Find All Duplicates in an Array
- Leetcode 442 - Find All Duplicates in an Array (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-Find All Duplicates in an Array
- [C语言][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 C++
- [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
- Find All Duplicates in an Array,leetcode,442
- LeetCode.442 Find All Duplicates in an Array
- Leetcode 442-Find All Duplicates in an Array
- 【442】Find All Duplicates in an Array
- 二维数组tip-tac-toe游戏
- 组原--动态RAM(DRAM)刷新方式
- OGNL的jar档、文档和源代码
- 如何在Qt中使用boost库
- Qt中文文档-QAbstractAxis类
- leetcode编程记录15 #442 Find All Duplicates in an Array
- 转载一篇文章:MNIST机器学习入门
- H3C交换机日常安全配置
- Qt之实现好友列表
- Qt的各版本直接下载地址
- JavaScript--利用变量来修改属性的小练习
- 数据结构与算法
- PDF文档如何加标签?哪个阅读器好用?
- 利用jQuery中的bgstretcher插件制作幻灯片效果背景