0

計算同時出現在2個陣列的數字

``````
public void Run()
{
Random seed = new Random();
int[] itemsA = new int[20000];
int[] itemsB = new int[20000];
for (int i = 0; i < 20000; i++)
{
itemsA[i] = seed.Next(10000);
itemsB[i] = seed.Next(10000);
}

DateTime now = DateTime.Now;
Console.WriteLine("同時出現在2個陣列的數字有 {0} 筆, 費時 {1:0.00}秒",
GetSameValues(itemsA, itemsB).Length, (DateTime.Now - now).TotalSeconds);
}

public int[] GetSameValues(int[] itemsA, int[] itemsB)
{
//請實作
throw new NotImplementedException();
}

``````

`````` for(int i = 0; i < itemsA.Length; i++)
{
for (int j = 0; j < itemsB.Length; j++)
{
if(itemsA[i] == itemsB[j])
{

}
}
}
``````

``````        public static int[] GetSameValues(int[] itemsA, int[] itemsB)
{
var intersect = itemsA.Intersect(itemsB);
int[] result = new int[0];
foreach (int id in intersect)
{
result = new int[id];

}

return result;
}
``````

3 個回答

1

iT邦大師 1 級 ‧ 2021-04-30 11:37:01

tenno081 iT邦新手 4 級 ‧ 2021-04-30 11:47:51 檢舉

0
theQuert
iT邦新手 5 級 ‧ 2021-04-30 11:48:05

tenno081 iT邦新手 4 級 ‧ 2021-04-30 11:53:19 檢舉

``````  public  int[] GetSameValues(int[] itemsA, int[] itemsB)
{
IEnumerable<int> intersect =                               itemsA.Intersect(itemsB);
return (int[])intersect;
}

``````

GetSameValues顯示需要有物件參考 才可使用非靜態欄位、方法或屬性

0
koro_michael
iT邦新手 3 級 ‧ 2021-04-30 12:05:47
``````using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
(new Program()).Run();
}

public void Run()
{
Random seed = new Random();
int[] itemsA = new int[20000];
int[] itemsB = new int[20000];
for (int i = 0; i < 20000; i++)
{
itemsA[i] = seed.Next(10000);
itemsB[i] = seed.Next(10000);
}

DateTime now = DateTime.Now;
Console.WriteLine("同時出現在2個陣列的數字有 {0} 筆, 費時 {1:0.00}秒",
GetSameValues(itemsA, itemsB).Length, (DateTime.Now - now).TotalSeconds);
}

public int[] GetSameValues(int[] itemsA, int[] itemsB)
{
IEnumerable<int> intersect = itemsA.Intersect(itemsB);
return intersect.ToArray();
}
}
``````

tenno081 iT邦新手 4 級 ‧ 2021-04-30 12:07:10 檢舉

tenno081 如果你想要自己實作的話

``````public int[] GetSameValues(int[] itemsA, int[] itemsB)
{
List<int> result = new List<int>();
HashSet<int> temp = new HashSet<int>();
foreach (int i in itemsB) {
}
foreach (int i in itemsA) {
if (temp.Remove(i)) {
}
}

return result.ToArray();
}
``````

tenno081 iT邦新手 4 級 ‧ 2021-04-30 12:24:50 檢舉