442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers
Posted Long Long Journey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers相关的知识,希望对你有一定的参考价值。
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 ≤ a[i] ≤ n 和 appear twice
解法:nums[Math.Abs(nums[i]) - 1] *= -1 如果 nums[Math.Abs(nums[i]) - 1] 小于0 则nums[i]重复
public class Solution {
public IList<int> FindDuplicates(int[] nums) {
List<int> list = new List<int>();
for (int i = 0; i < nums.Length; i++) {
nums[Math.Abs(nums[i]) - 1] *= -1;
if (nums[Math.Abs(nums[i]) - 1] > 0) {
list.Add(Math.Abs(nums[i]));
}
}
return list;
}
}
以上是关于442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers的主要内容,如果未能解决你的问题,请参考以下文章
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 (在数组中找到所有的重复项)