leetcode Day6 双指针法

118 阅读1分钟

344. 反转字符串

var reverseString = function(s) {
    let l=0,r=s.length-1
    while(l<r){
        let k=s[l]
        s[l]=s[r]
        s[r]=k
        l++
        r--
    }
    return s
};

206. 反转链表

var reverseList = function(head) {
    if(!head || !head.next)return head
    let node=head,pre=null,cur=null
    while(node){
        cur=node.next
        node.next=pre
        pre=node
        node=cur
    }
    return pre
};

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

var removeNthFromEnd = function(head, n) {
    let vhead=new ListNode(0,head)
    let slow=vhead,fast=vhead
    while(n>0){
        fast=fast.next
        n--
    }
    while(fast.next!=null){
        fast=fast.next
        slow=slow.next
    }
    slow.next=slow.next.next
    return vhead.next
};

142. 环形链表 II

var detectCycle = function(head) {
    if(!head || !head.next)return null
    let slow=head.next,fast=head.next.next
    while(fast && fast.next && slow!==fast){
        slow=slow.next
        fast=fast.next.next
    }
    if(!fast || !fast.next)return null
    slow=head
    while(slow!==fast){
        slow=slow.next
        fast=fast.next
    }
    return slow
};

15. 三数之和

var threeSum = function(nums) {
    if(nums.length<3)return []
    let res=[]
    nums.sort((a,b)=>a-b)
    for(let i=0;i<nums.length-2;i++){
        if(i>0 && nums[i]===nums[i-1])continue
        let l=i+1,r=nums.length-1
        while(l<r){
            if(nums[i]+nums[l]+nums[r]===0){
                res.push([nums[i],nums[l],nums[r]])
                while (l<r && nums[l] == nums[l+1]) l++; // 去重
                while (l<r && nums[r] == nums[r-1]) r--; // 去重
            }
            else if(nums[i]+nums[l]+nums[r]>0){
                r--
                continue
            }
            else{
                l++
                continue
            }
            l++
            r--
        }
    }
    return res
}

942. 增减字符串匹配

var diStringMatch = function(s) {
    let n=s.length
    let res=[]
    let min=0
    let max=n
    for(let i of s.split('')){
        if(i==='I'){
            res.push(min)
            min++
        }
        else{
            res.push(max)
            max--
        }
    }
    res.push(min)
    return res
};