[C#][LeetCode][Easy] 349. Intersection of Two Arrays

心得

題目要求找出兩個int[]交集的數字有哪些且不能重複並輸出。

問題

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

答案

  1. .NET提供的方法
1
2
3
4
5
6

public class Solution {
public int[] Intersection(int[] nums1, int[] nums2) {
return nums1.Intersect(nums2).ToArray();
}
}
  1. 上面那個方法太賤了,於是乎自己硬幹了一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

public class Solution {
public int[] Intersection(int[] nums1, int[] nums2) {
List<int> list = new List<int>();
Array.Sort(nums1);
Array.Sort(nums2);
for (int i = 0; i < nums1.Length; i++)
{
for (int j = 0; j < nums2.Length; j++)
{
if (nums1[i] == nums2[j])
{
if (list.Count == 0 || list[list.Count - 1] < nums1[i])
{
list.Add(nums1[i]);
}
break;
}
}
}

return list.ToArray();
}
}