[leetcode]442. Find All Duplicates in an Array

来源:互联网 发布:淘宝客复制别人的商品 编辑:程序博客网 时间:2024/05/22 11:44

Question:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appeartwice 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]


Answer:

public class Solution {    public List<Integer> findDuplicates(int[] nums) {        int[]  aa = new int[nums.length+1]; //注意数组大小是n+1        List<Integer> result = new ArrayList<Integer>();        for(int i=0;i<nums.length;i++) {        if(aa[nums[i]]!=0) {        result.add(nums[i]);        } else {        aa[nums[i]] = 1;        }        }        return result;    }}





0 0
原创粉丝点击