leetcode算法基础训练第三天:双指针

在这里插入图片描述在这里插入图片描述

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head){
            return head;//链表防范
        }
         ListNode*dummy=new ListNode(0,head);//防止头结点被删除先弄个哑结点
         ListNode*cur=dummy;
         while(cur->next&&cur->next->next){
             if(cur->next->val==cur->next->next->val){
                 int x=cur->next->val;
                 while(cur->next&&cur->next->val==x){
                     cur->next=cur->next->next;
                 }//如果结点等于这个值一直往后
             }
             else{
                 cur=cur->next;//下一个结点
             }
         }
         return dummy->next;//由哑结点返回链表
    }
};

在这里插入图片描述
这个是标准双指针问题的进阶,即三指针,多加一层循环罢了。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n=nums.size();
        sort(nums.begin(),nums.end());//sort函数排序
        vector<vector<int>> ans;//建一个二维数组作容器以待返回
        for(int first=0;first<n;first++){
            if(first>0&&nums[first]==nums[first-1]){
                continue;
            }//这个判定条件
            int third=n-1;
            int target=-nums[first];
            for(int second=first+1;second<n;second++){
                if(second>first+1&&nums[second]==nums[second-1]){
                    continue;
                }
                while(second<third&&nums[second]+nums[third]>target){
                    third--;//注意second<third
                }
                if(second==third){
                    break;//指针重合即可break
                }
                if(nums[second]+nums[third]==target){
                    ans.push_back({nums[first],nums[second],nums[third]});
                    //push_back函数的使用,注意大括号
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值