• Lc23-合并K个排序链表


    import java.util.ArrayList;
    import java.util.List;
    /**
     * 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
    
    示例:
    
    输入:
    [
      1->4->5,
      1->3->4,
      2->6
    ]
    输出: 1->1->2->3->4->4->5->6
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     *
     */
    public class Lc23 {
        // 暴力求解 全部拆下来希尔排序,然后重新组装
        public static ListNode mergeKLists(ListNode[] lists) {
    
            ListNode head = null;
            if (lists.length == 0 ) {
                return head;
            }
    
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < lists.length; i++) {
                ListNode node = lists[i];
                while (node != null) {
                    list.add(node.val);
                    node = node.next;
                }
            }
    
            
            //[{}] 这个测试用例 我不知道为什么可以存在,int为啥能为空
            if(list.size() == 0) {
                return head;
            }
            // 通过流的形式转化成数组
            int[] temp = list.stream().mapToInt(Integer::valueOf).toArray();
            shellSort(temp);
    
            // 转化成listNode, 这里需要借助双指针完成链表
            ListNode point = null;
            point = head = new ListNode(temp[0]);
            for (int i = 1; i < temp.length; i++) {
                point.next = new ListNode(temp[i]);
                point = point.next;
            }
            return head;
    
        }
    
        // 希尔排序
        private static void shellSort(int[] nums) {
            for (int gap = nums.length / 2; gap > 0; gap /= 2) {
                for (int i = gap; i < nums.length; i++) {
                    for (int j = i; j >= gap && nums[j - gap] > nums[j]; j -= gap) {
                        int temp = nums[j];
                        nums[j] = nums[j - gap];
                        nums[j - gap] = temp;
                    }
                }
            }
        }
    
    }
  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    基于分布式锁解决定时任务重复问题
    基于Redis的Setnx实现分布式锁
    基于数据库悲观锁的分布式锁
    使用锁解决电商中的超卖
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12199569.html
Copyright © 2020-2023  润新知