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;
}
}