码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 442. Find All Duplicates in an Array

时间:2017-02-19 20:22:27      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:element   do it   type   lis   给定一个整数数组   duplicate   时间复杂度   元素   root   

442. Find All Duplicates in an Array

Description Submission Solutions

  • Total Accepted: 16589
  • Total Submissions: 32282
  • Difficulty: Medium
  • Contributors: shen5630

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]

 Subscribe to see which companies asked this question.

【题目分析】

给定一个整数数组,数组中的元素都满足1 =< a[i] <= n。找出数组中重复出现的元素。要求不使用额外的存储空间,算法的时间复杂度是O(n)。

【思路分析】

对数组中的每个元素,把它当作数组的索引,把该索引对应位置的元素取反,如果发现该位置的元素已经取反,那么这个数就是重复出现的数。

【java代码】

 1 public class Solution {
 2     public List<Integer> findDuplicates(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         
 5         for(int i = 0; i < nums.length; i++) {
 6             int index = Math.abs(nums[i]) - 1;
 7             if(nums[index] < 0) {
 8                 res.add(index+1);
 9             }
10             nums[index] = -nums[index];
11         }
12         
13         return res;
14     }
15 }

 

LeetCode 442. Find All Duplicates in an Array

标签:element   do it   type   lis   给定一个整数数组   duplicate   时间复杂度   元素   root   

原文地址:http://www.cnblogs.com/liujinhong/p/6416666.html

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