leetcode解题模板 ——双指针

1.模板

/*(1)定义两个边界指针*/
int left = 0;//左边界
int right = num.size() - 1;//右边界
while(leftnext;//快指针
 while (s != f){/*执行操作*/}

2.实战
leetcode 42. 接雨水

class Solution {
public:
    int trap(vector& height) {
        if(height.size()<=2)return 0;
        int ans = 0;
        int left = 0;
        int right = height.size()-1;
        while(height[left]==0){left++;}
        while(height[right]==0){right--;}
        int lmax=height[left];
        int rmax=height[right];
        while(left

leetcode 75. 颜色分类

class Solution {
public:
    void sortColors(vector& nums) {
        if(nums.size() < 2){return;}
        int left = 0;
        int right = nums.size()-1;
        while(left0&&nums[right]==2)right--;
        while(left<=right){
           for(int i = left ; i<= right;i++){
            if(nums[i]==0){
                swap(nums[i],nums[left]);
                left++;
            }
            else if(nums[i]==2){
                swap(nums[i],nums[right]);
                right--;
            }
        } 
        }        
    }
};

leetcode 141. 环形链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr || head->next == nullptr){
            return false;
        }
        ListNode*s = head;
        ListNode*f = head->next;
        while(s != f){
            if(f == nullptr || f->next == nullptr){
                return false;
            }
            s = s->next;
            f = f->next->next;   
        }
        return true;
    }
};

leetcode解题模板 —— 目录

你可能感兴趣的:(leetcode解题模板,leetcode,指针,c++)