关于后端:287-寻找重复数-简单原地哈希运用题

2次阅读

共计 1550 个字符,预计需要花费 4 分钟才能阅读完成。

题目形容

这是 LeetCode 上的 287. 寻找反复数 ,难度为 中等

Tag :「桶排序」、「原地哈希」

给定一个蕴含 n + 1 个整数的数组 nums,其数字都在 $[1, n]$ 范畴内(包含 $1$ 和 $n$),可知至多存在一个反复的整数。

假如 nums 只有 一个反复的整数,返回 这个反复的数。

你设计的解决方案必须 不批改 数组 nums 且只用常量级 $O(1)$ 的额定空间。

示例 1:

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

输入:2

示例 2:

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

输入:3

提醒:

  • $1 <= n <= 10^5$
  • $nums.length = n + 1$
  • $1 <= nums[i] <= n$
  • nums 中 只有一个整数 呈现 两次或屡次,其余整数均只呈现 一次

进阶:

  • 如何证实 nums 中至多存在一个反复的数字?
  • 你能够设计一个线性级工夫复杂度 $O(n)$ 的解决方案吗?

原地哈希

数组长度为 $n + 1$,同时给定的 $nums[i]$ 都在 $[1, n]$ 范畴内,因而咱们能够设定哈希规定为 $nums[idx] = idx + 1$,即数值 x 会放在下标 $x – 1$ 的地位。

如此一来,对于只呈现一次的数值而言,必然可能顺利放在指标地位,而呈现屡次的数值必然会因为地位抵触而被找出。

Java 代码:

class Solution {public int findDuplicate(int[] nums) {for (int i = 0; i < nums.length;) {int t = nums[i], idx = t - 1;
            if (nums[idx] == t) {if (idx != i) return t;
                i++;
            } else {swap(nums, idx, i);
            }
        }
        return -1;
    }
    void swap(int[] nums, int i, int j) {int c = nums[i];
        nums[i] = nums[j];
        nums[j] = c;
    }
}

TypeScript 代码:

function findDuplicate(nums: number[]): number {for (let i = 0; i < nums.length;) {const t = nums[i], idx = t - 1
        if (nums[idx] == t) {if (idx != i) return t
            i++
        } else {swap(nums, i, idx)
        }
    }
    return -1
}
function swap(nums: number[], i: number, j: number): void {const c = nums[i]
    nums[i] = nums[j]
    nums[j] = c
}

Python 代码:

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        n, i = len(nums), 0
        while i < n:
            t, idx = nums[i], nums[i] - 1
            if nums[idx] == t:
                if idx != i:
                    return t
                i += 1
            else:
                nums[i], nums[idx] = nums[idx], nums[i]
        return -1
  • 工夫复杂度:$O(n)$
  • 空间复杂度:$O(1)$

最初

这是咱们「刷穿 LeetCode」系列文章的第 No.287 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,局部是有锁题,咱们将先把所有不带锁的题目刷完。

在这个系列文章外面,除了解说解题思路以外,还会尽可能给出最为简洁的代码。如果波及通解还会相应的代码模板。

为了不便各位同学可能电脑上进行调试和提交代码,我建设了相干的仓库:https://github.com/SharingSou…。

在仓库地址里,你能够看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其余优选题解。

更多更全更热门的「口试 / 面试」相干材料可拜访排版精美的 合集新基地 🎉🎉

本文由 mdnice 多平台公布

正文完
 0