LeetCode刷题:442. Find All Duplicates in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/seagal890/article/details/89056829

LeetCode刷题:442. Find All Duplicates in an Array

原题链接:https://leetcode.com/problems/find-all-duplicates-in-an-array/

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]

算法设计

package com.bean.algorithmexec;

import java.util.ArrayList;
import java.util.List;

public class FindAllDuplicates {
	
	 /*
	  * 输入参数为目标整型数组
	  * 开辟一个List,记为res
	  * */
	 public static List<Integer> findDuplicates(int[] nums) {
	        List<Integer> res = new ArrayList<>();
	        int[] count = new int[nums.length+1];      
	        for(int i=0; i < nums.length; ++i){
	            if(++count[nums[i]] > 1) 
	            	res.add(nums[i]);   
	        }    
	        return res;
	    }

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] demo = new int[]{4,3,2,7,8,2,3,1};
		List<Integer> result = findDuplicates(demo) ;
		for(int i=0;i<result.size();i++) {
			System.out.print(result.get(i)+"\t");
		}
		System.out.println();
		
	}

}

运行结果:输出

2 3

猜你喜欢

转载自blog.csdn.net/seagal890/article/details/89056829