LeetCode之Find All Duplicates in an Array
来源:互联网 发布:手机用usb使用电脑网络 编辑:程序博客网 时间:2024/06/08 15:34
本题的意思是给定一个整数数组,其中每个元素x都满足1 <= x <= n,其中n是该数组的元素数量。该数组中每个元素要么出现1次,要么出现2次。要求在不使用额外空间和在O(n)的时间复杂度内的条件下,找出所有出现2次的元素。
本题解法:从头至尾遍历该数组,将数组下标为当前访问的数组元素值减一的元素置为其本身的相反数(如果其本身现在是正数),那么如果以后再访问到与当前元素相同的元素,就会发现数组下标为当前访问的数组元素值减一的元素已经是负数了,就可以将这个当前访问的元素挑选出来,遍历完后,即可挑选出所有出现2次的元素。
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> dupl_; for (int i = 0; i < nums.size(); ++i) { int index = abs(nums[i]) - 1; if (nums[index] < 0) { dupl_.push_back(index + 1); } nums[index] = -nums[index]; } return dupl_; }};
阅读全文
0 0
- [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之Find All Duplicates in an Array
- leetcode之Find All Duplicates in an Array 问题
- Leetcode 442 - Find All Duplicates in an Array (array)
- LeetCode-Find All Duplicates in an Array & Find All Numbers Disappeared 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)
- [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(C++)(
- 【HTML】- 回到顶部
- 海量数据处理
- Matlab中max()函数的用法
- [LeetCode] 234. Palindrome Linked List
- 第7章 Spring MVC的高级技术--图片上传基于StandardServletMultipartResolver
- LeetCode之Find All Duplicates in an Array
- Python 实现LRU Cache
- Linux基础—>和>>的区别,<号的使用
- 网络请求的一些步骤和操作
- 注册表读取CPU信息
- Saliency Detection by Multi-Task Sparsity Puisuit
- html标签使用注意事项
- CUDA之同步函数详解
- 栈(ADT)