心得
題目要求找出兩個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.
答案
- .NET提供的方法
12345public class Solution {public int[] Intersection(int[] nums1, int[] nums2) {return nums1.Intersect(nums2).ToArray();}} - 上面那個方法太賤了,於是乎自己硬幹了一次
1234567891011121314151617181920212223public 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();}}