• 349. Intersection of Two Arrays


    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:

    public int[] Intersection(int[] nums1, int[] nums2) {
            var hashtable = new HashSet<int>();
            foreach(var n in nums1)
            {
                hashtable.Add(n);
            }
            var res = new List<int>();
            foreach(var n in nums2 )
            {
                if(hashtable.Contains(n) && !res.Contains(n))
                {
                    res.Add(n);
                }
            }
            return res.ToArray();
        }

    解法2:

    public int[] Intersection(int[] nums1, int[] nums2) {
            var res = new List<int>();
            Array.Sort(nums1);
            Array.Sort(nums2);
            int size1 = nums1.Count();
            int size2 = nums2.Count();
            int i = 0;
            int j = 0;
            int lastNumber =0;
            while(i<size1 && j<size2)
            {
                if(nums1[i] == nums2[j])
                {
                    if(res.Count()==0 || nums1[i] != res[res.Count()-1])
                    res.Add(nums1[i]);
                    i++;
                    j++;
                }
                else if(nums1[i] < nums2[j])
                {
                    i++;
                }
                else
                {
                    j++;
                }
            }
            return res.ToArray();
        }
  • 相关阅读:
    运算符,可变不可变数据类型
    基本的数据类型
    Python_day1
    day2_操作系统
    git fetch 命令
    Git branch 命令
    tmux常用命令
    转载-struts中logic标签使用
    转载-SVN常用命令
    javascript判断图片加载完成的三种方法
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5904809.html
Copyright © 2020-2023  润新知