LeetCode-442. Find All Duplicates in an Array

网友投稿 254 2022-08-29

LeetCode-442. Find All Duplicates in an Array

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]

题解:

class Solution {public: vector findDuplicates(vector& nums) { int n = nums.size(); vector res; for (int i = 0; i < n; i++) { int m = abs(nums[i]) - 1; if (nums[m] < 0) { res.push_back(m + 1); } nums[m] = -nums[m]; } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-416. Partition Equal Subset Sum
下一篇:舆情热议:央视网揭秘网红店营销套路!(网红营销现象)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~