Intersection of Two Arrays - C#
The question is from Leetcode:
Difficulty level: Easy
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
I’m coding this with C#.
My method is to use <List> data structure to store key info. First, I would declare num1, num2 as Int array and use the first array as the base. Compare num2[j] with every data in num1. Once it find the same, if no repetitive number in sol array, it will write the number into sol array and continue its looping.
My code:
public class Solution {
public int[] Intersection(int[] nums1, int[] nums2) {
List<int> sol = new List<int>(); //using List
for(int i = 0; i<nums1.Length; i++){
for(int j = 0; j<nums2.Length; j++){
if(nums2[j]==nums1[i]){
//if sol doesn’t contain the repetitive data.
if(!sol.Contains(nums2[j])) {
sol.Add(nums2[j]); // Add element to sol
}
}
break; // No need to compare the rest of the element
}
}
return sol.ToArray();
}
public void Main(string[] args){
Solution solution = new Solution();
string nums1_str = Console.ReadLine();
string nums2_str = Console.ReadLine();
// Splite the whole string into string array
string[] nums1_strs = nums1_str.Split(' ');
string[] nums2_strs = nums2_str.Split(' ');
// Parse the string array into int array
int[] nums1 = Array.ConvertAll(nums1_strs, int.Parse);
int[] nums2 = Array.ConvertAll(nums2_strs, int.Parse);
// Call Intersection method and print result
int[] result = solution.Intersection(nums1, nums2);
foreach (int num in result)
Console.WriteLine(num);
}
}