Leetcode 442. 数组中重复的数据
本文最后更新于208 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com

1.题目基本信息

1.1.题目描述

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

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

1.2.题目地址

https://leetcode.cn/problems/find-all-duplicates-in-an-array/description/

2.解题方法

2.1.解题思路

思路1:原地哈希。将数组中数量只有1个的元素x交换到下标为x-1的位置,将索引值作为哈希的键;将有两个的元素y,其中一个交换到下标为y-1的位置,另一个交换到数组中不存在的元素z对应的下标z-1处;最后统计数组中索引+1和值不相等的数量即为题解。

思路2:正负号标记。将已经遍历到的数字x,对应的nums[x-1]的值转为负号,即标记了x的存在,也保留了nums[x-1]原来值的信息。

3.解题代码

python代码

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        # 思路2:正负号标记。将已经遍历到的数字x,对应的nums[x-1]的值转为负号,即标记了x的存在,也保留了nums[x-1]原来值的信息。
        n = len(nums)
        result = []
        for i in range(n):
            x = abs(nums[i])
            if nums[x - 1] > 0:
                nums[x - 1] = -nums[x - 1]
            else:
                result.append(x)
        return result

    def findDuplicates1(self, nums: List[int]) -> List[int]:
        # 思路1:原地哈希。将数组中数量只有1个的元素x交换到下标为x-1的位置,将索引值作为哈希的键;将有两个的元素y,其中一个交换到下标为y-1的位置,另一个交换到数组中不存在的元素z对应的下标z-1处;最后统计数组中索引+1和值不相等的数量即为题解。
        n = len(nums)
        for i in range(n):
            while nums[i] != nums[nums[i] - 1]:
                p = nums[i]
                nums[i], nums[p - 1] = nums[p - 1], nums[i]
        result = []
        for i in range(n):
            if i != nums[i] - 1:
                result.append(nums[i])
        return result

c++代码

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> result;
        int n = nums.size();
        for (int i = 0; i < n; i++) {
            int x = abs(nums[i]);
            if (nums[x - 1] > 0) {
                nums[x - 1] = -nums[x - 1];
            } else {
                result.push_back(x);
            }
        }
        return result;
    }
};

4.执行结果

觉得有帮助可以投喂下博主哦~感谢!

作者:geek007

转载请注明文章地址及作者哦~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇