LeetCode-Find All Duplicates in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82346957

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]

题意:给定一个一维数组,长度为n,数组中的所有元素的范围在区间[1,n];现要求找出在数组中重复出现至少两次的元素;

解法:根据题意我们知道数组中所有元素出现的范围在区间[1,n]之间,因此,我们可以对数组进行标记,每个元素将其数字的绝对值对应下标位置减1处的元素置为负数,这样我们在下次只需要判断当前对应下标是否为负,就可以知道这个元素是否重复;

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

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82346957