leetcode 442 数组中重复的数据

版权声明:copy-right:BHY https://blog.csdn.net/WallBreakerBhy/article/details/84099995

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次

找到所有出现两次的元素。

你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

显然,若可以使用额外空间,利用set的特性,判断nums[i]是否存在set中,若存在则此数时重复的,记录下来并将set中的该数删除,若不存在则将其放入set中即可。

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        Set<Integer> set = new TreeSet<>();
        for(int num:nums){
            if(set.contains(num)){
                res.add(num);
                set.remove(num);
            }
            else{
                set.add(num);
            }
        }
        return res;
    }
}

另外,考虑不使用额外空间的算法:

题目中没有提到不能改变数组元素的值,因此可以利用元素的正负性来进行技术。同时,因为1<=nums[i]<=n,所以每个元素都对应着另一个元素的索引,当我们遍历到nums[i]时,将Math.abs(nums[i]-1)对应的元素取反,意味着nums[i]出现一次,如果nums[Math.abs(nums[i])-1]的值在取反之后变回正值,则说明在此之前nums[i]已经出现过了,将nums[i]记录下来即可。

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

猜你喜欢

转载自blog.csdn.net/WallBreakerBhy/article/details/84099995