1.模板
/*(1)定义两个边界指针*/
int left = 0;//左边界
int right = num.size() - 1;//右边界
while(left<right){/*执行操作*/}
/*(2)定义两个快慢指针*/
ListNode*s = head;//慢指针
ListNode*f = head->next;//快指针
while (s != f){/*执行操作*/}
2.实战
leetcode 42. 接雨水
class Solution {
public:
int trap(vector<int>& 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<right){
if(height[left]<=height[right]){
if(lmax<height[left])lmax=height[left];
ans = ans-height[left]+lmax;
left++;
}
else{
if(rmax<height[right])rmax=height[right];
ans = ans-height[right]+rmax;
right--;
}
}
return ans;
}
};
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.size() < 2){return;}
int left = 0;
int right = nums.size()-1;
while(left<right&&nums[left]==0)left++;
while(right>0&&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--;
}
}
}
}
};
/**
* 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;
}
};