leetcode442. Find All Duplicates in an Array

来源:互联网 发布:网络硬盘录像机 交换机 编辑:程序博客网 时间:2024/05/22 13:27

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;    }}

这里写图片描述

0 0
原创粉丝点击