LeetCode.442 Find All Duplicates in an Array

来源:互联网 发布:衣服品牌查询软件 编辑:程序博客网 时间:2024/05/21 10:35

题目:

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]

分析:

class Solution {    public List<Integer> findDuplicates(int[] nums) {        //给定数组,长度为n,其中元素范围1-n,其中有些元素重复出现一次或者两次,找出所有重复的元素        //要求:在没有额外空间和运行时间不为O(n)        //思路:用一个长度为n+1的数组记录各出现次数        List<Integer> list=new ArrayList<>();                //因为可能存在数值为n的元素,需要存入count[n]的下标中        int [] count=new int[nums.length+1];                for(int i=0;i<nums.length;i++ ){            count[nums[i]]++;            if(count[nums[i]]==2){                list.add(nums[i]);            }        }        return list;                  }}


原创粉丝点击