码迷,mamicode.com
首页 > 编程语言 > 详细

442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers

时间:2017-03-11 12:50:42      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:example   runtime   auto   back   lan   appear   this   round   return   

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]重复
  1. public class Solution {
  2. public IList<int> FindDuplicates(int[] nums) {
  3. List<int> list = new List<int>();
  4. for (int i = 0; i < nums.Length; i++) {
  5. nums[Math.Abs(nums[i]) - 1] *= -1;
  6. if (nums[Math.Abs(nums[i]) - 1] > 0) {
  7. list.Add(Math.Abs(nums[i]));
  8. }
  9. }
  10. return list;
  11. }
  12. }





442. 找出数组中重复的元素 Find All Duplicates in an ArrayGiven an array of integers

标签:example   runtime   auto   back   lan   appear   this   round   return   

原文地址:http://www.cnblogs.com/xiejunzhao/p/fd62258e250caf4f07840c19bb9fac0d.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!