zoukankan      html  css  js  c++  java
  • [LeetCode] 349. Intersection of Two Arrays 两个数组相交

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

    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]

    Note:

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

    解法:由于结果中要求元素是唯一的,所以用set来统计num1 中的数字。再循环num2中的数字,在set中存在就记录到结果中,同时从set中删除。

    Java: HashSet, T: O(n)

    class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
           HashSet<Integer> set = new HashSet<Integer>();
            ArrayList<Integer> res = new ArrayList<Integer>();
            //Add all elements to set from array 1
            for(int i =0; i< nums1.length; i++) set.add(nums1[i]);
            for(int j = 0; j < nums2.length; j++) {
               // If present in array 2 then add to res and remove from set 
               if(set.contains(nums2[j])) {
                    res.add(nums2[j]);
                    set.remove(nums2[j]);
                }
            }
            // Convert ArrayList to array
            int[] arr = new int[res.size()];
            for (int i= 0; i < res.size(); i++) arr[i] = res.get(i);
            return arr;        
        }
    }  

    Java: Hashset T: O(n)

    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>();
            Set<Integer> intersect = new HashSet<>();
            for (int i = 0; i < nums1.length; i++) {
                set.add(nums1[i]);
            }
            for (int i = 0; i < nums2.length; i++) {
                if (set.contains(nums2[i])) {
                    intersect.add(nums2[i]);
                }
            }
            int[] result = new int[intersect.size()];
            int i = 0;
            for (Integer num : intersect) {
                result[i++] = num;
            }
            return result;
        }
    }
    

    Java: two points, T: O(nlogn)

    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>();
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int i = 0;
            int j = 0;
            while (i < nums1.length && j < nums2.length) {
                if (nums1[i] < nums2[j]) {
                    i++;
                } else if (nums1[i] > nums2[j]) {
                    j++;
                } else {
                    set.add(nums1[i]);
                    i++;
                    j++;
                }
            }
            int[] result = new int[set.size()];
            int k = 0;
            for (Integer num : set) {
                result[k++] = num;
            }
            return result;
        }
    }
    

    Java: Binary Search, T: O(nlogn)  

    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>();
            Arrays.sort(nums2);
            for (Integer num : nums1) {
                if (binarySearch(nums2, num)) {
                    set.add(num);
                }
            }
            int i = 0;
            int[] result = new int[set.size()];
            for (Integer num : set) {
                result[i++] = num;
            }
            return result;
        }
        
        public boolean binarySearch(int[] nums, int target) {
            int low = 0;
            int high = nums.length - 1;
            while (low <= high) {
                int mid = low + (high - low) / 2;
                if (nums[mid] == target) {
                    return true;
                }
                if (nums[mid] > target) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            }
            return false;
        }
    } 

    Python:

    class Solution(object):
        def intersection(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            res = []
            s = set()
            for num in nums1:
                s.add(num)
                
            for num in nums2:
                if num in s:
                    res.append(num)
                    s.remove(num)
                    
            return res 
    

    Python:

    class Solution(object):
        def intersection(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            nums1=set(nums1)
            nums2=set(nums2)
            return list(nums1&nums2) 

    C++:

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            set<int> s(nums1.begin(), nums1.end()), res;
            for (auto a : nums2) {
                if (s.count(a)) res.insert(a);
            }
            return vector<int>(res.begin(), res.end());
        }
    };
    

    C++:

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            vector<int> res;
            int i = 0, j = 0;
            sort(nums1.begin(), nums1.end());
            sort(nums2.begin(), nums2.end());
            while (i < nums1.size() && j < nums2.size()) {
                if (nums1[i] < nums2[j]) ++i;
                else if (nums1[i] > nums2[j]) ++j;
                else {
                    if (res.empty() || res.back() != nums1[i]) {
                        res.push_back(nums1[i]);
                    }
                    ++i; ++j;
                }
            }
            return res;
        }
    };
    

      

    类似题目:

    [LeetCode] 350. Intersection of Two Arrays II 两个数组相交II 

    [LeetCode] 160. Intersection of Two Linked Lists 求两个链表的交集

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    成长历程
    读书笔记javascript基本数据类型
    箭头函数
    sql server管理 这些你懂吗?
    索引的创建原则
    VisualStudio2012新特性[路边社通稿]
    第一节 MongoDB介绍及下载与安装
    sql server复灾 你懂了吗?
    错误处理:......标记为系统必备,必须对其进行强签名 收藏
    那么什么是好的代码呢?
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9583997.html
Copyright © 2011-2022 走看看