数组中重复的数据

LC442. 数组中重复的数据

给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。

你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。

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

思路:原地正负号标志

  • 遍历 nums,得到值 num,将 num 对应的位置的数 *(-1),再判断此数是否是正数,是的话则表示出现两次
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int n = nums.length;
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int x = Math.abs(nums[i])-1;
            nums[x] *= -1;
            if (nums[x] > 0) {
                res.add(x+1);
            }
        }
        return res;
    }
}
updatedupdated2022-06-232022-06-23