3Sum——筆記

1581674751476.png

問題

  1. 如何去除重得到的重復(fù)組?
  2. python和c++中的不同方式;

解決

        while(front < rear){

                if(nums[i] + nums[front] + nums[rear]==0){
                    vector<int> factor;
                    factor.push_back(nums[i]);
                    factor.push_back(nums[front]);
                    factor.push_back(nums[rear]);
                    res.push_back(factor);
                    cout<<nums[i]<<nums[front]<<nums[rear]<<endl;

                    front++;
                    rear--;
                    
                    while(front < rear && nums[front] == nums[front-1])
                        front++;

                    while(front < rear && nums[rear] == nums[rear+1])
                        rear--;
                    
                }
                else if(nums[i] + nums[front] +nums[rear] > 0){
                    rear--;
                }
                else{
                    front++;
                }
            }
  1. 通過將兩個(gè)指針去除重復(fù)數(shù)值,實(shí)現(xiàn)指針中的去重復(fù)值
while(front < rear && nums[front] == nums[front-1])
         front++;
while(front < rear && nums[rear] == nums[rear+1])
         rear--;

important??!

實(shí)現(xiàn)查找可以向前查找,或者向后查找,分別是:

A: nums[front] == nums[front-1]

B: nums[front] == nums[front+1]

這種方法的不同點(diǎn)在于,在完成后==0條件后是否進(jìn)行front和rear指針的跳轉(zhuǎn);

? 討論:

1. A方式實(shí)現(xiàn)向后查找,就是先進(jìn)行指針跳轉(zhuǎn);
2. B方式實(shí)現(xiàn)向前跳轉(zhuǎn),步驟是先排除重復(fù)數(shù)值,然后進(jìn)行front和rear指針跳轉(zhuǎn);
if(i > 0 && nums[i]==nums[i-1])  continue;

這一步就是實(shí)現(xiàn) i 移動時(shí),排除重復(fù)值,此處就是向前查找

  1. python和c++中的不同方式;

最終結(jié)果是格式[[1,2,-3],[1,0,-1]......]

c++:

題目是 vector<vector<int>> 進(jìn)行;

c++排序:sort(nums.begin() , nums.end())

python:List[List[int]]

python的排序:nums.sort()

圖一說明
此圖引用大佬的圖,侵權(quán)立刪,非常感謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容