leetcode349&350

1、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.
感覺這個做法十分簡單粗暴,就是把兩個數組排好順序,從前到後的比較,相同就放入result,同時後移接着比較,一大一小就後移小的,就醬~
最後把result的重複的清空偷懶用了兩個STL函數嘻嘻~~
然鵝效率還可以~~

class Solution{
public:
    vector<int> intersection(vector<int> & num1,vector<int> & num2){
        vector<int> result;
        int s1,s2;
        s1=num1.size();
        s2=num2.size();
        sort(num1.begin(),num1.end());
        sort(num2.begin(),num2.end());
        for(int i = 0,j = 0;i < s1 && j < s2;){
            if(num1[i]==num2[j]){
                result.push_back(num1[i]);
                i++;
                j++;
            }
            else if(num1[i]>num2[j])
                j++;
            else
                i++;

        }
        result.erase(unique(result.begin(), result.end()), result.end());
        return result;
    }
};

1、

iterator erase (const_iterator position);//刪一個
iterator erase (const_iterator first, const_iterator last);//刪一段

Removes from the vector either a single element (position) or a range of elements ([first,last)).
2、

ForwardIterator unique (ForwardIterator first, ForwardIterator last);

返回An iterator to the element that follows the last element not removed.
unique只是把重複的元素放到容器的後面,而它本身會返回一個迭代器,只向這些元素的開始部分,舉個栗子~

int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10
std::vector<int> myvector (myints,myints+9);

std::vector<int>::iterator it;
it = std::unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 

2、Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
與上面題唯一的區別就是不用去重,就是把倒數第二句刪掉就好了~

class Solution{
public:
    vector<int> intersect(vector<int> & num1,vector<int> & num2){
        vector<int> result;
        int s1,s2;
        s1=num1.size();
        s2=num2.size();
        sort(num1.begin(),num1.end());
        sort(num2.begin(),num2.end());
        for(int i = 0,j = 0;i < s1 && j < s2;){
            if(num1[i]==num2[j]){
                result.push_back(num1[i]);
                i++;
                j++;
            }
            else if(num1[i]>num2[j])
                j++;
            else
                i++;

        }
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章