442. 数组中重复的数据——Java

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array

方法一:排序

  1. nums[] 排序
  2. nums[i] == nums[i - 1] 则为重复
public static List<Integer> findDuplicates(int[] nums) {
    
    
    Arrays.sort(nums);
    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 1; i < nums.length; i++) {
    
    
        if (nums[i] == nums[i - 1])
            list.add(nums[i]);
    }
    return list;
}

方法二:取负

  1. 遍历数组,若索引 Math.abs(nums[i]) - 1处的数字为正,记为负
  2. 若索引 Math.abs(nums[i]) - 1处的数字为负,添加到 list 集合
public static List<Integer> findDuplicates2(int[] nums) {
    
    
  ArrayList<Integer> list = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
    
    
        if (nums[Math.abs(nums[i]) - 1] > 0)
            nums[Math.abs(nums[i]) - 1] *= -1;
        else
            list.add(Math.abs(nums[i]));
    }
    return list;
}

猜你喜欢

转载自blog.csdn.net/m0_46390568/article/details/107949113
今日推荐