快慢指针
ListNode head; // 头节点
head.next; //下一节点
head.val; //节点对应值
是否为循环链表,利用快慢指针
当快慢指针相等时说明为循环列表
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(slow != fast ){
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
普通指针
LeetCode - 第二题
定义链表的头节点,head.next
注意l1和l2要非空
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode newList = head;
int jinyi = 0;
// ListNode n1 = l1;
// ListNode n2 = l2;
while(l1 != null || l2 != null || jinyi != 0 ){
int n1 = l1 != null ? l1.val : 0 ;
int n2 = l2 != null ? l2.val : 0 ;
if ((n1 + n2 + jinyi) >= 10){
int num = (n1 + n2 + jinyi) % 10 ;
newList.next = new ListNode(num);
newList = newList.next;
jinyi = (n1 + n2 + jinyi) / 10;
}else{
int num = n1 + n2 + jinyi;
newList.next = new ListNode(num);
newList = newList.next;
jinyi = 0;
}
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
}
return head.next;
}
}
对撞指针
对撞指针
利用对撞指针,首先对数组进行排序,当两数之和大于载重,则大的一方单独需要一艘船,j–。
当两数之和小于载重,大的一方减一,小的一方加一:j–,i++;
当i==j时,只剩一人,也需要一艘船,num++;
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int i = 0 ;
int j = people.length - 1;
int num = 0;
while( i < j){
if((people[i] + people[j]) > limit) {
num++;
j--;
}else{
j--;
i++;
num++;
}
if(i == j){
num++;
}
}
return num;
}
}