题目链接

数组中重复的数据

题目描述

image.png

解题思路

方法一:空间换时间

  1. class Solution {
  2. public List<Integer> findDuplicates(int[] nums) {
  3. List<Integer> result = new ArrayList<>();
  4. int len = nums.length;
  5. int[] temp = new int[len+1];
  6. for(int i=0; i<len; i++) {
  7. if(++temp[nums[i]] == 2) {
  8. result.add(nums[i]);
  9. }
  10. }
  11. return result;
  12. }
  13. }

方法二:正负号做标记

由于给定的 n 个数都在 [1,n] 的范围内,如果有数字出现了两次,就意味着 [1,n] 中有数字没有出现过;
因此,我们可以尝试将每一个数放在对应的位置。由于数组的下标范围是[0,n−1],我们需要将数 i 放在数组中下标为 i−1 的位置:

  • 如果 i恰好出现了一次,那么将 i 放在数组中下标为 i-1 的位置即可;
  • 如果 i 出现了两次,那么我们希望其中的一个 i 放在数组下标中为 i-1 的位置,另一个 i 放置在任意「不冲突」的位置 j。也就是说,数 j+1 没有在数组中出现过。

我们也可以给 nums[i] 加上「负号」表示数 i+1 已经出现过一次。具体地,我们首先对数组进行一次遍历。当遍历到位置 i 时,我们考虑 nums[nums[i]−1] 的正负性:

  1. 如果 nums[nums[i]−1] 是正数,说明 nums[i] 还没有出现过,我们将 nums[nums[i]−1] 加上负号;
  2. 如果 nums[nums[i]−1] 是负数,说明 nums[i] 已经出现过一次,我们将 nums[i] 放入答案
    1. class Solution {
    2. public List<Integer> findDuplicates(int[] nums) {
    3. int n = nums.length;
    4. List<Integer> ans = new ArrayList<Integer>();
    5. for (int i = 0; i < n; ++i) {
    6. int x = Math.abs(nums[i]);
    7. if (nums[x - 1] > 0) {
    8. nums[x - 1] = -nums[x - 1];
    9. } else {
    10. ans.add(x);
    11. }
    12. }
    13. return ans;
    14. }
    15. }