leetcode:2023/4/7

1040.移动石子直到连续II
在这里插入图片描述

class Solution {
    public int[] numMovesStonesII(int[] stones) {
        int n = stones.length;
        Arrays.sort(stones);
        if (stones[n - 1] - stones[0] + 1 == n) {
            return new int[]{0, 0};
        }
        int ma = Math.max(stones[n - 2] - stones[0] + 1, stones[n - 1] - stones[1] + 1) - (n - 1);
        int mi = n;
        for (int i = 0, j = 0; i < n && j + 1 < n; ++i) {
            while (j + 1 < n && stones[j + 1] - stones[i] + 1 <= n) {
                ++j;
            }
            if (j - i + 1 == n - 1 && stones[j] - stones[i] + 1 == n - 1) {
                mi = Math.min(mi, 2);
            } else {
                mi = Math.min(mi, n - (j - i + 1));
            }
        }
        return new int[]{mi, ma};
    }
}


876.链表的中间结点

在这里插入图片描述

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode[] A=new ListNode[100];
        int t=0;
        while(head!=null){
            A[t++]=head;
            head=head.next;
        }
        return A[t/2];
    }
}

数组法
class Solution {
    public ListNode middleNode(ListNode head) {
       ListNode slow=head,fast=head;
       while(fast!=null&&fast.next!=null){
           slow=slow.next;
           fast=fast.next.next;
       }
       return slow;
    }
}

快慢指针法
class Solution {
    public ListNode middleNode(ListNode head) {
       int n=0;
       ListNode cur=head;
       while(cur!=null){
           ++n;
           cur=cur.next;
       }
       int k=0;
       cur=head;
       while(k<n/2){
           ++k;
           cur=cur.next;
       }
       return cur;
    }
}
单指针法

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

在这里插入图片描述

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy=new ListNode(0,head);
        ListNode first=head;
        ListNode second=dummy;
        for(int i=0;i<n;++i){
            first=first.next;
        }
        while(first!=null){
            first=first.next;
            second=second.next;
        }
        second.next=second.next.next;
        ListNode ans=dummy.next;
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值