牛客网 BM5合并K个已排序链表
首先写出和并两个已排序链表的方法,然后用分治法合并k个链表
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类ArrayList
* @return ListNode类
*/
public ListNode mergeKLists (ArrayList<ListNode> lists) {
return mergeKListNodes(lists, 0, lists.size()-1);
}
ListNode mergeKListNodes(ArrayList<ListNode> lists,int n, int m){//分治法
if(n > m)return null;
else if(n == m) return lists.get(n);
int mid = (n + m)/2;
return mergeListNode(mergeKListNodes(lists, n, mid), mergeKListNodes(lists, mid + 1, m));
}
public ListNode mergeListNode(ListNode pHead1, ListNode pHead2){
ListNode ans = new ListNode(-1);
ListNode pre1 = pHead1;
ListNode pre2 = pHead2;
ListNode pre = ans;
while(pre1 != null && pre2 != null){
if(pre1.val < pre2.val){
pre.next = pre1;
pre1 = pre1.next;
pre = pre.next;
}
else{
pre.next = pre2;
pre2 = pre2.next;
pre = pre.next;
}
}
if(pre1 != null){
pre.next = pre1;
}
else{
pre.next = pre2;
}
return ans.next;
}
}
BM6 判断链表是否有环
法一:双指针
import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode slow = head;
ListNode fast = head;
while(slow != null && fast != null){
slow = slow.next;
if(fast.next != null){
fast = fast.next.next;
}else return false;
if(slow == fast){
return true;
}
}
return false;
}
}
法二:set集合
import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode ans = head;
Set<ListNode> node = new HashSet<ListNode>();
while(ans != null){
if(node.contains(ans)){
return true;
}
node.add(ans);
ans = ans.next;
}
return false;
}
}
BM7链表中环的入口
法一:hashset第一个contatins();
法二:快慢指针如果到环结点的距离为k,环的长度为l。当slow点到达结点,fast离结点为k,两者相差l-k。则经过l-k后两者相聚,s离结点l-k,经过k步到达结点。————相聚后令fast=head,第一个相遇点及入口。