双指针

快慢指针

LeetCode 141.环形链表

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* slow=head;
        ListNode* fast=head;
        while((fast!=NULL)&&(fast->next!=NULL)){
            slow=slow->next;
            fast=fast->next->next;
            if(fast==slow){//如果存在环,快指针迟早会追上慢指针
                return true;
            }
        }
        return false;
    }
};

LeetCode 876. 链表的中间结点

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* slow=head;
        ListNode* fast=head;
        while((fast!=nullptr)&&(fast->next!=nullptr)){
            slow=slow->next;//n+1
            fast=fast->next->next;//2n+1;
        }
        return slow;
    }
};

LeetCode 19. 删除链表的倒数第 N 个结点

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* slow=head;
        ListNode* fast=head;
        while(n-->0){//快指先行n步
            fast=fast->next;
        }
        if(fast==nullptr){
            return head->next;
        }
        while((fast!=nullptr)&&(fast->next)!=nullptr){
            slow=slow->next;
            fast=fast->next;
        }
        slow->next=slow->next->next;
        return head;
    }
};

其他应用

LeetCode 167. 两数之和 II - 输入有序数组

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int left=0;
        int right=numbers.size()-1;
        vector<int> ans;
        while(left<right){//不断调整,大了小一点,小了大一点
            if(numbers[left]+numbers[right]==target){
                break;
            }else if(numbers[left]+numbers[right]>target){
                right--;
            }else if(numbers[left]+numbers[right]<target){
                left++;
            }
        }
        ans.push_back(left+1);
        ans.push_back(right+1);
        return ans;
    }
};

LeetCode 344. 反转字符串

class Solution {
public:
    void reverseString(vector<char>& s) {
        int left=0;
        int right=s.size()-1;
        while(left<right){
            char temp=s[left];
            s[left]=s[right];
            s[right]=temp;
            left++;
            right--;
        }
    }
};
posted @ 2021-06-10 14:44  niu_a  阅读(21)  评论(0编辑  收藏  举报