【LeetCode】442. Find All Duplicates in an Array(找出数组中的重复项)

【LeetCode】442. Find All Duplicates in an Array(找出数组中的重复项)

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

问题描述:

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]

解释:数组中的数字可能出现一次或两次,让我们找出所有出现两次的数字返回就行了。但是注意:题目要求必须是在时间O(N)内,而且不能用额外的空间,所以类似于冒泡类的O(N^2)就不能用了。

方法一:

注意:题目中的1 ≤ a[i] ≤ n (n = size of array),这一点很重要,所以a[i]-1就正好可以做数组a[]的下标,仔细想一想a[i]和a[a[i]-1]的关系。然后我们来分析一下,没有额外的空间,就只能在这个数组上动手脚了,请看代码:

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; ++i) {
            int index = Math.abs(nums[i])-1;
            if (nums[index] < 0)
                res.add(Math.abs(index+1));
            nums[index] = -nums[index];
        }
        return res;
    }
}

此方法的思路是 当遍历num[i]时,我们让num[num[i]-1]取相反数,这样,当我们再一次遇到这个数时,num[num[i]-1]为负就可以判断这个数重复出现了。例如当我们第一次遍历,nums[i]=4,那么就让nums[3]=-nums[3],7就会变成-7,所以当我们再一次遇到4,那么nums[3]=-7<0,所以就加入到res中即可,以此类推。

方法二:

这种方法是将nums[i]置换到其对应的位置nums[nums[i]-1]上去,比如对于没有重复项的正确的顺序应该是[1, 2, 3, 4, 5, 6, 7, 8],而我们现在却是[4,3,2,7,8,2,3,1],我们需要把数字移动到正确的位置上去,比如第一个4就应该和7先交换个位置,变成[7,3,2,4,8,2,3,1],7和3交换位置,变成[3,3,2,4,8,2,7,1],直到第一个数字变为1,第一个位置遍历完毕,以此类推,最后得到顺序[1, 2, 3, 4, 3, 2, 7, 8],最后在对应位置检验,如果nums[i]和i+1不等,那么我们将nums[i]存入结果res中即可。

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer>list=new ArrayList<Integer>();
        int temp;
        for(int i=0;i<nums.length;i++)
        {
            int tem=nums[i]-1;
            if(nums[i]!=nums[tem])
            {
                temp=nums[i];
                nums[i]=nums[tem];
                nums[tem]=temp;
                i--;
            }
        }
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]!=i+1)
                list.add(nums[i]);
        }
        return list;
    }
}

暂时就先写这两种方法吧,以后有空接着补充


日期:2018/2/9-18:10

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值