测试开发备战秋招面试5-牛客刷题之链表篇

news2024/10/5 18:30:08

趁着5.1假期把牛客网的必刷的TOP101过一遍,额,题目量有点大,争取5天给刷完吧,哈哈,加油啦。再用雷布斯的那句话来激励自己吧:努力了那么多年,回头一望,几乎全是漫长的挫折和煎熬。对于大多数人的一生来说,顺风顺水只是偶尔,挫折、不堪、焦虑和迷茫才是主旋律。

 

一、链表篇

1.1、反转链表

题目链接:反转链表_牛客题霸_牛客网

思路:构造一个新链表,每次把原链表的一个节点摘下来作为新链表的头节点,即可实现反转。

Java版:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
      //双链表法实现链表反转,每次摘掉的链表,使其成为新链表的头节点
      ListNode newHead = null ;
      while(head != null){
        //把头节点摘下来,为新链表的头节点
        ListNode tmp = head.next ;
        head.next = newHead ;
        newHead = head ;
        //继续向后走
        head = tmp ;
      }
      return newHead ;

    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def ReverseList(self , head: ListNode) -> ListNode:
        # write code here
        if not head:
            return None

        newHead = ListNode(head.val)
        head = head.next 
        while head:
            tmp = head.next 
            head.next = newHead 
            newHead = head 
            head = tmp 
        return newHead

1.2、链表内指定区间的反转

题目链接:链表内指定区间反转_牛客题霸_牛客网

思路:构造一个带头节点的新链表,遍历到指定m位置,每次修改三次指针,最后去掉新链表的头节点就是反转后的链表。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        //指定区间内反转链表,只需要在原来的基础之上找到相应位置开始反转
        ListNode newH = new ListNode(-1) ;
        newH.next = head ;
        ListNode pre = newH ;
        ListNode cur =  head ;
        for(int i=1; i<m; i++){
            pre = cur ;
            cur = cur.next ;
        }
        //每次摘掉一个节点,放到当前节点的前面
        for(int i=m; i<n; i++){
            ListNode tmp = cur.next ;
            cur.next = tmp.next ; //让2指向4
            tmp.next = pre.next ; //让3指向2
            pre.next = tmp ; //将1指向3          
        }
        return newH.next ;

    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param m int整型 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
        # write code here
        newH = ListNode(-1)
        newH.next = head
        pre = newH
        cur = head

        for i in range(1,m):
            pre = cur 
            cur = cur.next 
        
        for i in range(m,n):
            tmp = cur.next 
            cur.next = tmp.next
            tmp.next = pre.next
            pre.next = tmp 
        
        return newH.next

1.3、链表中的节点每k个一组翻转

题目链接:链表中的节点每k个一组翻转_牛客题霸_牛客网

思路:借助栈实现,每次k个节点入栈,出栈后拼接到一起,不满足k个的则直接拼接即可。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        //借助栈实现链表的反转,每次k个节点入栈,节点出栈反转
        ListNode res = new ListNode(1) ;
        ListNode p = res ;
        while(true){
            Stack<ListNode> stack = new Stack<>() ;
            int cnt = k ;
            ListNode tmp = head ;
            while(cnt!=0 && head != null){
                stack.push(head) ;
                head = head.next ;
                cnt -- ;
            }
            if(cnt != 0){
                p.next = tmp ;
                break ;
            }
            while(!stack.isEmpty()){
                p.next = stack.pop() ;
                p = p.next ;
            }
        }
        return res.next ;
    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
        # write code here
        newHead = ListNode(-1)
        p = newHead
        while True:
            stack = []
            cnt = k
            tmp = head 
            while cnt and head:
                stack.append(head)
                head = head.next
                cnt = cnt - 1
            if  cnt:
                p.next = tmp 
                break 
            while stack:
                p.next = stack.pop()
                p = p.next 
        return newHead.next 

1.4、合并两个排序的链表

题目链接:合并两个排序的链表_牛客题霸_牛客网

思路:迭代法和递归法都可以实现,这里构建一个新的空链表,遍历两个链表,依次将小的值拼接上去就可以了。

Java版:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
      //迭代法
      ListNode node = new ListNode(-1) ;
      ListNode cur = node ;

      while(list1 != null && list2 != null){
        if(list1.val <= list2.val){
            cur.next = list1 ;
            list1 = list1.next ;
        }else{
            cur.next = list2 ;
            list2 = list2.next ;
        } 
        cur = cur.next ;     
      }
      cur.next = list1 == null ? list2 : list1 ;
      return node.next ;
    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        # write code here
        h = ListNode(0)
        p = h
        while pHead1 and pHead2:
            if pHead1.val <= pHead2.val:
                p.next = pHead1
                pHead1 = pHead1.next 
            else:
                p.next = pHead2
                pHead2 = pHead2.next
            p = p.next 
        if  pHead1:
            p.next = pHead1
        if  pHead2:
            p.next = pHead2
        return h.next 

1.5、判断链表是否有环

题目链接:判断链表中是否有环_牛客题霸_牛客网

思路:快慢指针,需要注意是节点相同,而不是仅仅是节点的值相同,还有循环条件要设置好。

Java版本:

/**
 * 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 || head.next == null){
        return false ;
      }
      ListNode fast = head ;
      ListNode slow = head ;
      while(fast != null && fast.next != null){
        fast = fast.next.next ;
        slow = slow.next ;
        if(slow == fast){
            return true ;
        }
      }
      return false ;

    }
}

Python版本:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param head ListNode类 
# @return bool布尔型
#
class Solution:
    def hasCycle(self , head: ListNode) -> bool:
        
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next 
            slow = slow.next
            if slow == fast:
                return True
        return False

1.6、链表中环的入口结点

题目链接:链表中环的入口结点_牛客题霸_牛客网

思路:快慢指针,相遇后,相遇节点距离环入口点的距离和起点距离入口节点的距离相等。

Java版:

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
      ListNode fast = pHead ;
      ListNode slow = pHead ;
      if(pHead == null || pHead.next == null){
        return null ;
      }
      while(fast != null && fast.next != null){
        fast = fast.next.next ;
        slow = slow.next ;
        if(slow == fast){
            fast = pHead ;
            break ;
        }
        if(slow == null || fast == null){
            return null ;
        }
      }
      while(slow != fast){
        slow = slow.next ;
        fast = fast.next ;
      }
      return fast ;
      
    }
}

Python版:

from contextlib import nullcontext
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        # write code here
        slow  = pHead
        fast = pHead
        if not pHead or not pHead.next:
            return None
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                fast = pHead
                break
            if  not slow or not fast:
                return None
        while fast != slow:
            fast = fast.next 
            slow = slow.next
        return fast 

1.7、链表中倒数最后k个结点

题目链接:链表中倒数最后k个结点_牛客题霸_牛客网

思路:计算链表长度len,然后向后遍历,找到len-k开头的链表就是倒数最后k个节点。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        int len = 0 ;
        ListNode cur = pHead ;
        while(cur != null){
            cur = cur.next ;
            len ++ ;
        }
        if(k>len){
            return null ;
        }
        for(int i=0; i<len-k; i++){
            pHead = pHead.next ;
        }
        return pHead ;

    }
}

Python版:

from contextlib import nullcontext
from pickle import NONE
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        l = 0
        cur = pHead 
        while cur:
            cur = cur.next 
            l  = l + 1 
        j = l - k 
        if j < 0 :
            return None
        while j > 0:
            pHead = pHead.next 
            j  = j - 1
        return pHead

1.8、删除链表的倒数第n个节点

题目链接:删除链表的倒数第n个节点_牛客题霸_牛客网

思路:计算链表长度,然后修改链表指针删除第n个节点,如果是第一个节点,则直接返回去除头节点的链表。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        
        ListNode res = head ;
        int len = 0 ;
        ListNode tmp = res ;
        ListNode cur = head ;
        while(cur != null){
            cur = cur.next ;
            len ++ ;
        }
        int j = len - n  ;
        if(j==0){
            return res.next ;
        }
        while(j>0){
            tmp = head ;
            head = head.next ;
            j -- ;
        }
       
        tmp.next = tmp.next.next ;
        return res ;
    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param n int整型 
# @return ListNode类
#
class Solution:
    def removeNthFromEnd(self , head: ListNode, n: int) -> ListNode:
        # write code here
        l = 0
        cur = head
        tmp = res = head
        while cur:
            cur = cur.next
            l = l + 1
        j = l - n 
        if j == 0 :
            return head.next
        while j > 0 :
            tmp = head
            head = head.next
            j  = j - 1
        tmp.next = tmp.next.next 
        return res 

1.9、两个链表的第一个公共节点

题目链接:两个链表的第一个公共结点_牛客题霸_牛客网

思路:长的链表的长度-短链表长度=n,则长的先跑n,然后长短链表一起跑,并判断是否有公共节点。

Java版:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int len1 = 0, len2 = 0 ;
        ListNode p1 = pHead1 ;
        ListNode p2 = pHead2 ;
        while(p1 != null){
            p1 = p1.next ;
            len1 ++ ;
        }
        while(p2 != null){
            p2 = p2.next ;
            len2 ++ ;
        }
        int dur = len1 - len2 >= 0 ? len1 - len2 : len2 - len1 ;
        if(len1 >= len2){
            for(int i=0; i<dur; i++){
                pHead1 = pHead1.next ;
            }
        }else{
            for(int i=0; i<dur; i++){
                pHead2 = pHead2.next ;
            }
        }
        while(pHead1 != null && pHead2 != null){
            if(pHead1 == pHead2){
                 return pHead1 ;
                }
                pHead1 = pHead1.next ;
                pHead2 = pHead2.next ;
            }
        return null ;
    }
}


Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        p1 = pHead1
        p2 = pHead2
        l1 = l2 = 0
        while p1:
            p1 = p1.next
            l1 = l1 + 1
        while p2:
            p2 = p2.next
            l2 = l2 + 1
        if(l1 >= l2):
            for i in range(0,l1-l2):
                pHead1 = pHead1.next 
        else:
            for i in range(0,l2-l1):
                pHead2 = pHead2.next
        while(pHead1 and pHead2):
            if pHead1 == pHead2:
                return pHead1
            pHead1 = pHead1.next 
            pHead2 = pHead2.next
        return None

1.10、链表相加(二)

题目链接:链表相加(二)_牛客题霸_牛客网

思路:借助栈的后进先出的思想,依次累加元素,并拼接到新链表的头部。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        //借助栈的先进后出功能实现
        Stack<ListNode> stack1 = new Stack<>() ;
        Stack<ListNode> stack2 = new Stack<>() ;

        ListNode h1 = head1 ;
        ListNode h2 = head2 ;
        ListNode p =  null ;

        while(h1 != null){
            stack1.push(h1) ;
            h1 = h1.next ;
        }
        while(h2 != null){
            stack2.push(h2) ;
            h2 = h2.next ;
        }
        int v = 0 ;
        while(!stack1.isEmpty() || !stack2.isEmpty()){
            if(!stack1.isEmpty()){
                v += stack1.pop().val ;
            }
            if(!stack2.isEmpty()){
                v += stack2.pop().val ;
            }
            ListNode node = new ListNode(v%10) ;
            node.next = p ;
            p = node ;
            v = v/10 ;
        }
        if(v > 0){
            ListNode node1 = new ListNode(v) ;
            node1.next = p ;
            p = node1 ;
        }

        return p ;
        
    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        stack1 = []
        stack2 = []
        p1 = ListNode(0)
        p = p1.next
        while head1:
            stack1.append(head1)
            head1 = head1.next 
        while head2:
            stack2.append(head2)
            head2 = head2.next 
        cnt = 0 
        while stack1 or stack2:
            if stack1 :
                cnt = cnt + stack1.pop().val
            if stack2:
                cnt = cnt + stack2.pop().val
            tmp = ListNode(cnt%10)
            tmp.next = p
            p = tmp
            cnt = cnt // 10
        if cnt :
            tmp1 = ListNode(cnt)
            tmp1.next = p
            p = tmp1
        return p
        

1.11、单链表的排序

题目链接:单链表的排序_牛客题霸_牛客网

思路:用集合给元素排序,然后依次改变链表元素的值就可以了。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        List<Integer> list = new ArrayList<>() ;
        ListNode h = head ;
        ListNode p = h ;
        while(h != null){
            list.add(h.val) ;
            h = h.next ;
        }
        Collections.sort(list) ;
        for(int i=0; i<list.size(); i++){
            head.val = list.get(i) ;
            head = head.next ;
        }
        return p ;

    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 the head node
# @return ListNode类
#
class Solution:
    def sortInList(self , head: ListNode) -> ListNode:
        # write code here
        lst = []
        p = h = head 
        while h:
            lst.append(h.val)
            h = h.next 
        lst.sort()
        for l in lst:
            head.val = l
            head = head.next
        return p

1.12、判断一个链表是否为回文结构

题目链接:判断一个链表是否为回文结构_牛客题霸_牛客网

思路:借助栈,依次比对即可。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        Stack<ListNode> stack = new Stack<>() ;
        ListNode h = head ;
        while(h!=null){
            stack.push(h) ;
            h = h.next ;
        }
        while(!stack.isEmpty()){
            ListNode s = stack.pop() ;
            if(s.val != head.val){
                return false ;
            }
            head = head.next ;
        }
        return true ;
    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 the head
# @return bool布尔型
#
class Solution:
    def isPail(self , head: ListNode) -> bool:
        # write code here
        stack = []
        h = head
        while h:
            stack.append(h)
            h = h.next 
        while stack:
            if stack.pop().val != head.val:
                return False
            head = head.next 
        return True

1.13、 链表的奇偶重排

题目链接:链表的奇偶重排_牛客题霸_牛客网

思路:List集合记录奇数和偶数位置的数字,然后依次更改原链表的数值即可。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode oddEvenList (ListNode head) {
        // write code here
        int cnt = 1 ;
        ListNode p = head ;
        ListNode tmp = head ;
        List<Integer> odd = new ArrayList<>() ;
        List<Integer> even = new ArrayList<>() ;
        while(p != null){
            if(cnt%2==1){
                odd.add(p.val) ;
            }else{
                even.add(p.val) ;
            }
            cnt ++ ;
            p = p.next ;
        }
        int i = 0, j = 0 ;
        while(tmp != null){
            if(i < odd.size()){
                tmp.val = odd.get(i) ;
                i ++ ;
            }else{
                tmp.val = even.get(j) ;
                 j ++ ;
            }
            tmp = tmp.next ;
        }
        return head ;

    }
}

Python版:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def oddEvenList(self , head: ListNode) -> ListNode:
        # write code here
        lst1 = []
        lst2 = []
        s = 1 
        p = h = head
        while p:
            if s%2==1:
                lst1.append(p.val)
            else:
                lst2.append(p.val)
            s  = s + 1
            p = p.next 
        i = j = 0 
        while head:
            if i < len(lst1):
                head.val = lst1[i]
                i = i + 1
            else:
                head.val = lst2[j]
                j = j + 1
            head = head.next
        return h

1.14、删除有序链表中重复的元素-I

题目链接:删除有序链表中重复的元素-I_牛客题霸_牛客网

思路:借助队列实现,删除重复元素。

Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        Queue<Integer> queue = new LinkedList<>() ;
        ListNode  p = head ;
        ListNode cur = head ;
        while(p != null){
            queue.offer(p.val) ;
            p = p.next ;
        }
        while(cur != null){
            int v = queue.poll() ;
            if(!queue.contains(v)){
                cur.val = v ;
                cur = cur.next ;
            }else{
                cur.next = cur.next.next ;
            }
            
        }
        return head ;
        

    }
}

1.15、删除有序链表中重复的元素-II

题目链接:删除有序链表中重复的元素-II_牛客题霸_牛客网

思路:用map记录,不过在之前next,应该在最后再去掉头元素。
Java版:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        ListNode p = head ;
        ListNode h = new ListNode(-1);
        ListNode newH = h ;
        Map<Integer,Integer> map = new TreeMap<>() ;
        
        while(p != null){
            if(map.containsKey(p.val)){
                map.put(p.val,map.get(p.val)+1) ;
            }else{
                map.put(p.val, 1) ;
            }
            p = p.next ;
        }
        while(head != null){
            if(map.get(head.val) == 1){
                h.next = new ListNode(head.val) ;
                h = h.next ;
            }
            head = head.next ;
        }
        return newH.next ;
    }
}

1.16、合并k个已排序的链表

题目链接:合并k个已排序的链表_牛客题霸_牛客网

思路:借助辅助数组,获取所有链表元素并排序,然后拼接到一起就可以了。

Java版:

import java.util.*;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        ListNode p = new ListNode(-1) ;
        ListNode h = p ;
        ArrayList<Integer> lst = new ArrayList<>() ;
        for(ListNode tmp : lists){
            while(tmp != null){
                lst.add(tmp.val) ;
                tmp = tmp.next ;
            }
        }
        Collections.sort(lst) ;
        for(Integer v : lst){
            p.next = new ListNode(v) ;
            p = p.next ;
        }
        return h.next  ;
    }
}


Python版:

from re import L
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param lists ListNode类一维数组 
# @return ListNode类
#
class Solution:
    def mergeKLists(self , lists: List[ListNode]) -> ListNode:
        # write code here
        lst = []
        p =  ListNode(-1)
        h = p 
        for list in lists:
            while list:
                lst.append(list.val)
                list = list.next
        lst.sort()
        for v in lst:
            p.next = ListNode(v)
            p = p.next
        return h.next 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/479721.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

学习Python需要注意什么?分享一下如何提升写代码的质量

作为程序员&#xff0c;每天都会面对各种各样的问题和挑战。需求的变更、代码的维护和修复、测试的问题&#xff0c;以及线上出现的各种异常等等&#xff0c;这些都需要我们不断地投入精力去解决。但是&#xff0c;我们不能只关注在解决问题上&#xff0c;还需要关注代码质量。…

IDE - Android Studio/Xcode历史版本下载

文章目录 前言Android Studio1. 历史版本下载2. 文件完整性校验 Xcode1. 历史版本下载2. 网络环境模拟工具2.1 下载2.2 安装2.3 卸载 最后 前言 最近升级开发工具老是遇到各种兼容性问题导致需要降回老版本&#xff0c;Xcode历史版本下载方便倒还好&#xff0c;Android Studio…

使用pands.rolling方法实现移动窗口的聚合计算

一个问题举例 假设有一个5天的收益数据&#xff0c;需要每3天求出一次平均值来达成某个需求&#xff1a; daterevenue2023-05-01102023-05-02202023-05-03302023-05-04402023-05-0550 1号、2号和3号的数据求一次平均值&#xff0c;2号、3号和4号的数据求一次平均值&#xff…

Ucore lab4

实验目的 了解内核线程创建/执行的管理过程了解内核线程的切换和基本调度过程 实验内容 练习一&#xff1a;分配并初始化一个进程控制块 1.内核线程及管理 内核线程是一种特殊的进程&#xff0c;内核线程与用户进程的区别有两个&#xff1a;内核线程只运行在内核态&#x…

内网渗透(六十一)之Kerberosating攻击

Kerberosating攻击 Kerberosating攻击发生在Kerberos协议的TGS_REP阶段,KDC的TGS服务返回一个由服务Hash 加密的ST给客户端。由于该ST是用服务Hash进行加密的,因此客户端在拿到该ST后可以用于本地离线爆破。如果攻击者的密码字典足够强大,则很有可能爆破出SPN链接用户的明文…

JAVA入坑之GUI编程

一、相关概述 GUI编程是指通过图形化的方式来实现计算机程序的编写&#xff0c;它可以让用户通过鼠标、键盘等设备来操作计算机&#xff0c;而不是通过命令行来输入指令。在Java中&#xff0c;GUI编程主要使用的是Swing和AWT两种技术 二、AWT 2.1介绍 AWT是Java提供的用来建立…

【构造】CF851div2 C. Matching Numbers

Problem - C - Codeforces 题意&#xff1a; 有1~2*n的一个排列&#xff0c;进行数与数之间两两匹配&#xff0c;问如何组合可以使n个 数对 aibi排列起来是一个连续序列&#xff0c;如果无解输出No 思路&#xff1a; 构造题&#xff0c;考虑将构造的条件特殊化 手推样例可知…

【数据生成】——Semantic Image Synthesis via Diffusion Models语义分割数据集生成论文浅读

语义分割&#xff0c;数据生成 摘要 Denoising Diffusion Probabilistic Models (DDPMs) 在各种图像生成任务中取得了显著的成功&#xff0c;相比之下&#xff0c;生成对抗网络 (GANs) 的表现不尽如人意。最近的语义图像合成工作主要遵循事实上的基于 GAN 的方法&#xff0c;…

QT QHBoxLayout 水平布局控件

本文详细的介绍了QHBoxLayout控件的各种操作&#xff0c;例如&#xff1a;新建界面、添加控件、布局控件、显示控件、添加空白行、设置间距 、添加间距、设置位置、设置外边距、设置边距、添加固定宽度、方向上、方向下、方向左、方向右等等、 样式表等操作。 实际开发中&#…

无距离障碍:远程桌面Ubuntu实现全球办公【内网穿透】

目录 前言 视频教程 1. ubuntu安装XRDP 2.局域网测试连接 3. Ubuntu安装cpolar内网穿透 4.cpolar公网地址测试访问 5.固定域名公网地址 [TOC] 转载自远程穿透文章&#xff1a;Windows通过RDP异地远程桌面Ubuntu【内网穿透】 前言 XRDP是一种开源工具&#xff0c;它允许…

范数详解-torch.linalg.norm计算实例

文章目录 二范数F范数核范数无穷范数L1范数L2范数 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。 范数是一种数学概念&#xff0c;可以将向量或矩阵映射到非负实数上&#xff0c;通常被…

Python使用pytorch深度学习框架构造Transformer神经网络模型预测红酒分类例子

1、红酒数据介绍 经典的红酒分类数据集是指UCI机器学习库中的Wine数据集。该数据集包含178个样本&#xff0c;每个样本有13个特征&#xff0c;可以用于分类任务。 具体每个字段的含义如下&#xff1a; alcohol&#xff1a;酒精含量百分比 malic_acid&#xff1a;苹果酸含量&a…

Python之硬汉巴特勒

一、前言 2023年4月27日&#xff0c;NBA季后赛热火4:1淘汰雄鹿&#xff0c;实现黑八。全NBA联盟最硬气的男人——巴特勒&#xff0c;再次向全世界证明了他是NBA最硬气的男人。上一场刚狂轰56分大比分逆转雄鹿&#xff0c;这一场又是带领球队打出了血性&#xff0c;超高难度绝平…

快速搭建简单图床 - 远程访问本地搭建的EasyImage图床【内网穿透】

文章目录 1.前言2. EasyImage网站搭建2.1. EasyImage下载和安装2.2. EasyImage网页测试2.3.cpolar的安装和注册 3.本地网页发布3.1.Cpolar云端设置3.2 Cpolar本地设置 4. 公网访问测试5. 结语 1.前言 一个好的图床&#xff0c;是网站或者文章图片能稳定显示的关键&#xff0c;…

驱动管理软件推荐

最近发现电脑右下角的任务栏中有一个叹号图标&#xff0c;如下&#xff1a; 点进去之后发现是Windows自家的安全中心的内核隔离出现了点问题&#xff0c;内核隔离功能打不开 点击“查看不兼容的驱动程序”&#xff0c;发现是一些驱动作祟 我的电脑中显示了好多不兼容的驱动程序…

跟着我学习 AI丨语音识别:将语音转为数字信号

语音识别是一种人工智能技术&#xff0c;其主要目的是将人类说话转化为计算机可以理解的信息。语音识别技术的应用非常广泛&#xff0c;包括智能家居、汽车导航、语音搜索、人机交互、语音翻译等。 语音识别的技术原理 语音识别的技术原理是将人类的语音信号转化为数字信号。这…

『python爬虫』06. 数据解析之re正则解析(保姆级图文)

目录 1. 什么是re解析2. 正则规则元字符量词匹配模式测试 3. 正则案例4. re模块的使用4.1 findall: 匹配字符串中所有的符合正则的内容4.2 finditer: 匹配字符串中所有的内容[返回的是迭代器]4.3 search, 找到一个结果就返回, 返回的结果是match对象4.4 match 从头开始匹配&…

Windows forfiles命令详解,Windows按时间搜索特定类型的文件。

「作者简介」&#xff1a;CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者 「推荐专栏」&#xff1a;对网络安全感兴趣的小伙伴可以关注专栏《网络安全入门到精通》 forfiles 一、结果输出格式二、按时间搜索三、搜索指定类型文件四、批量删除文件 forfile…

Ubuntu远程SSH连接与远程桌面连接

目录 一、远程桌面连接 二、远程SSH连接 1、安装客户端 2、安装服务端 3、SSH客户端和服务端的区别 一、远程桌面连接 首先需要在Ubuntu里进行些设置&#xff0c;点击界面右上角的控制区&#xff0c;选择设置选项&#xff1b; 弹出界面进入网络中&#xff0c;点击设置图…

【致敬未来的攻城狮计划】— 连续打卡第十八天:FSP固件库开发GPT — PWM输出波形 — LED呼吸灯

系列文章目录 1.连续打卡第一天&#xff1a;提前对CPK_RA2E1是瑞萨RA系列开发板的初体验&#xff0c;了解一下 2.开发环境的选择和调试&#xff08;从零开始&#xff0c;加油&#xff09; 3.欲速则不达&#xff0c;今天是对RA2E1 基础知识的补充学习。 4.e2 studio 使用教程 5.…