LeetCode 349. Intersection of Two Arrays

来源:互联网 发布:mui.js下载 编辑:程序博客网 时间:2024/06/07 05:39

When i first see this question, I don’t know how to complete it. I am not that familiar with c++’s vector or something like that. After looked up in the website, i know i should use set.

c++:

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {        set<int> a;        vector <int> rslt;        for(int i=0; i<nums1.size(); i++){            a.insert(nums1[i]);        }        for(int i=0; i<nums2.size(); i++){            if(a.find(nums2[i])!=a.end()){                a.erase(nums2[i]);                rslt.push_back(nums2[i]);            }        }        return rslt;    }};
  • set insert: set.insert()
  • set.find: if not found, it will return set.end()
  • vector insert: vector.push_back()
  • vector.insert(position, value)
  • vector length: vector.size()

Java

can use HashSet<\integer>, see Link:
http://blog.csdn.net/mebiuw/article/details/51448806

Python

Python is a little easier:

class Solution(object):    def intersection(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        relt=set();        for num in nums1:            if num in nums2:                relt.add(num)        return list(relt)
  • set.add(i)
  • list.append(i)
0 0
原创粉丝点击