leetcode442. Find All Duplicates in an Array

数组中重复数字查找
本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下找出数组中所有重复数字的方法。通过两种不同的实现方式:一是改变数组元素值来标记已访问的状态,二是利用负数标记已经检查过的元素。

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]

解法一

判断数组的中的某一项值是否已经发生变化。如num[i]=7, 对7-1=6,num[6]的位置发生变化,如果7只出现一次,则num[6]变化一次;如果7只出现两次,而num[6]已经发生了变化,则找到原来的值6+1.

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }

        int len = nums.length;
        for (int i = 0; i < nums.length; i++) {
            int index = (nums[i] - 1) % len;
            if (nums[index] > len) {
                ret.add(index + 1);
            } else {
                nums[index] += len;
            }
        }

        return ret;
    }
}

这里写图片描述

解法二

判断某一项是否为负数。

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }

        for (int i = 0; i < nums.length; i++) {
            int index = Math.abs(nums[i]) - 1;
            if (nums[index] < 0) {
                ret.add(index + 1);
            } else {
                nums[index] *= -1;
            }
        }

        return ret;
    }
}

这里写图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值