当前位置: 代码迷 >> 综合 >> C#找出数组中重复的数字
  详细解决方案

C#找出数组中重复的数字

热度:11   发布时间:2024-01-25 05:59:57.0

找出数组中重复的数字

解1:时间复杂度O(n),空间复杂度O(n)的解法

using System;
using System.Collections;
using System.Collections.Generic;namespace CSharpTest01
{class Program{// 找出数组中重复的数字static Hashtable FindRepeat(int[] dataList){Hashtable repeatTable = new Hashtable();Dictionary<int, int> dict = new Dictionary<int, int>();for (int i = 0; i < dataList.Length; i++){dict[dataList[i]] = 0;}for (int i = 0; i < dataList.Length; i++){int key = dataList[i];if (dict[key] == 1){repeatTable.Add(key, 0);}dict[key] = 1;}return repeatTable;}static void Main(string[] args){int[] dataList = new int[7] { 2, 5, 7, 9, 3, 2, 7 };Hashtable hashtable = FindRepeat(dataList);foreach (var item in hashtable.Keys){Console.WriteLine(item);}}}
}

解2:时间复杂度O(n),空间复杂度O(1)

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:输入: [1,3,4,2,2]
输出: 2
示例 2:输入: [3,1,3,4,2]
输出: 3
说明:不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。

using System;namespace CSharpTest01
{class Program{// 找出数组中重复的数字/* 快慢指针的思想,tortoise和hare是指针,nums[tortoise]表示取对应的元素* 注意nums中的数字都是1-n之间的,所以在数组中游走不会越界* 因为有重复数字的出现,所以这个游走必然是成环的,环的入口就是重复的元素* 即按照寻找链表环入口来做*/static int FindRepeat(int[] nums){// Find the intersection point of the two runners.int tortoise = nums[0];int hare = nums[0];do{tortoise = nums[tortoise];hare = nums[nums[hare]];} while (tortoise != hare);// Find the "entrance" to the cycle.int ptr1 = nums[0];int ptr2 = tortoise;while (ptr1 != ptr2){ptr1 = nums[ptr1];ptr2 = nums[ptr2];}return ptr1;}static void Main(string[] args){int[] nums = new int[5] { 3, 1, 3, 4, 2 };//int[] nums = new int[5] { 1, 3, 4, 2, 2 };int repeatNum = FindRepeat(nums);Console.WriteLine(repeatNum);Console.ReadKey();}}
}

 

  相关解决方案