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

发布时间:2026/10/6 9:34:00
在长度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) 。

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询