首页 > 其他 > 详细

LeetCode 442. Find All Duplicates in an Array

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!