Leetcode 442. Find All Duplicates in an Array

本文介绍了一种用于查找数组中重复元素的有效算法。该算法利用数组元素的特性,通过标记已遍历过的元素来快速找到重复项。适用于元素值介于1到n之间的整数数组,且每个元素最多出现两次。
/**
 * As described in the problem, 
 * 1 ≤ a[i] ≤ n (n = size of array)
 * therefore, we can use nums[nums[i]] = -nums[nums[i]] to help us which elements 
 * appear twice. Note that elements in the array appear at most twice. 
 */ 
public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int index;
        List<Integer> res = new ArrayList<Integer>();
        
        for (int i=0; i<nums.length; i++) {
            index = Math.abs(nums[i]);
            if (nums[index-1] < 0) res.add(index);
            else nums[index-1] = -nums[index-1];
        }
        return res;
    }
}

Similar problem, Leetcode 448. Find All Numbers Disappeared in an Array
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值