zoukankan      html  css  js  c++  java
  • 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();
        }
  • 相关阅读:
    Spring restful
    LDAP & Implementation
    Restful levels and Hateoas
    事务隔离的级别
    servlet injection analysis
    session and cookie
    write RE validation
    hello2 source analysis
    匿名函数和递归函数
    生成器和迭代器,列表推导式
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5904809.html
Copyright © 2011-2022 走看看