返回介绍

solution / 0400-0499 / 0442.Find All Duplicates in an Array / README_EN

发布于 2024-06-17 01:04:00 字数 3306 浏览 0 评论 0 收藏 0

442. Find All Duplicates in an Array

中文文档

Description

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return _an array of all the integers that appears twice_.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

 

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Example 2:

Input: nums = [1,1,2]
Output: [1]

Example 3:

Input: nums = [1]
Output: []

 

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 1 <= nums[i] <= n
  • Each element in nums appears once or twice.

Solutions

Solution 1

class Solution:
  def findDuplicates(self, nums: List[int]) -> List[int]:
    for i in range(len(nums)):
      while nums[i] != nums[nums[i] - 1]:
        nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
    return [v for i, v in enumerate(nums) if v != i + 1]
class Solution {
  public List<Integer> findDuplicates(int[] nums) {
    int n = nums.length;
    for (int i = 0; i < n; ++i) {
      while (nums[i] != nums[nums[i] - 1]) {
        swap(nums, i, nums[i] - 1);
      }
    }
    List<Integer> ans = new ArrayList<>();
    for (int i = 0; i < n; ++i) {
      if (nums[i] != i + 1) {
        ans.add(nums[i]);
      }
    }
    return ans;
  }

  void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
  }
}
class Solution {
public:
  vector<int> findDuplicates(vector<int>& nums) {
    int n = nums.size();
    for (int i = 0; i < n; ++i) {
      while (nums[i] != nums[nums[i] - 1]) {
        swap(nums[i], nums[nums[i] - 1]);
      }
    }
    vector<int> ans;
    for (int i = 0; i < n; ++i) {
      if (nums[i] != i + 1) {
        ans.push_back(nums[i]);
      }
    }
    return ans;
  }
};
func findDuplicates(nums []int) []int {
  for i := range nums {
    for nums[i] != nums[nums[i]-1] {
      nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
    }
  }
  var ans []int
  for i, v := range nums {
    if v != i+1 {
      ans = append(ans, v)
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文