本文共 1012 字,大约阅读时间需要 3 分钟。
LeetCode刷题:442. 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 ListfindDuplicates(int[] nums) { List 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 result = findDuplicates(demo) ; for(int i=0;i
程序运行结果:
2 3
转载地址:http://witdi.baihongyu.com/