尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

在长度2N的数组中找出重复N次的元素(四)

发布时间:2026/9/20 8:28:13

资讯中心
01
ARTICLE

在长度2N的数组中找出重复N次的元素(四)

在长度2N的数组中找出重复N次的元素(四)
方法三随机选择思路与算法我们可以每次随机选择两个不同的下标判断它们对应的元素是否相等即可。如果相等那么返回任意一个作为答案。代码Cclass Solution { public: int repeatedNTimes(vectorint nums) { int n nums.size(); mt19937 gen{random_device{}()}; uniform_int_distributionint dis(0, n - 1); while (true) { int x dis(gen), y dis(gen); if (x ! y nums[x] nums[y]) { return nums[x]; } } } };Javaclass Solution { public int repeatedNTimes(int[] nums) { int n nums.length; Random random new Random(); while (true) { int x random.nextInt(n), y random.nextInt(n); if (x ! y nums[x] nums[y]) { return nums[x]; } } } }C#public class Solution { public int RepeatedNTimes(int[] nums) { int n nums.Length; Random random new Random(); while (true) { int x random.Next(n), y random.Next(n); if (x ! y nums[x] nums[y]) { return nums[x]; } } } }Python3class Solution: def repeatedNTimes(self, nums: List[int]) - int: n len(nums) while True: x, y random.randrange(n), random.randrange(n) if x ! y and nums[x] nums[y]: return nums[x]Cint repeatedNTimes(int* nums, int numsSize) { srand(time(NULL)); while (true) { int x random() % numsSize, y random() % numsSize; if (x ! y nums[x] nums[y]) { return nums[x]; } } }复杂度分析时间复杂度期望 O(1) 。选择两个相同元素的概率为 n/2n*(n-1)/2n≈1/4 因此期望 44 次结束循环。空间复杂度O(1) 。
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。