Sort List 【leetCode】

目录:

1、题目及分析

1.1 题目

1.2 分析



1、题目及分析

1.1 题目:

Sort a linked list in O(n log n)
time using constant space complexity.

1.2 分析

O(n log n)的复杂度,所以不能采用冒泡等,这里采用合并排序算法,且为了不采用递归的方式,所以得到如下代码。

2、实现

 // Definition for singly-linked list.
  class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }

public class SortList {

    public int length(ListNode head){ //求链表的长度
        int count = 0;
        ListNode h = head;
        while(null != h){
            count ++;
            h = h.next;
        }
        return count;
    }
    public ListNode sortList(ListNode head) {//返回排序的结果
        int len = length(head);
        //System.out.println(len);
        int window = 2;//
        ListNode pointL = null;
        ListNode pointR = null;
        ListNode tmp = null;
        ListNode tmp2 = null;
        ListNode headPointer = new ListNode(0); //定义一个头指针
        ListNode headPointerTmp = head;         //定义一个暂头指针
        headPointer.next = head;    //将头指针指向传入的链表
        headPointerTmp = headPointer;      //暂存头指针指向头指针
        if(0 == len || 1== len) return head; //如果长度为1,则直接返回

        while(window/2 < len){  //二分法每个区间用2^n大小表示,如果len=5,那么必须运算到window=8才能结束
                                //这里采用 len大于window/2 当len=5时,8/2=4仍然运行,16/2=8才结束
            for(int i=len ; i>0; i-=window){
                pointL = headPointerTmp;
                pointR = headPointerTmp;

                for(int k=window/2; k>0; k--){
                    if(null == pointR.next) break;
                    pointR =  pointR.next;//移动指针
                }

                for(int j=window/2; j>0; )  {//由于使用分治,所有待排序的,都已经按照一定顺序排列
                                             //R的操作最多window/2次
                    if(pointR == pointL || null == pointR.next) break; //L中所有都遍历了就结束
                    if(pointR.next.val < pointL.next.val){//满足条件则进行插入操作
                        /* pre->A->B->C>D  要将C插入到A之前
                         * pointL = pre; pointR = C;
                         * pre->C;C->A;B->D
                         */
                        tmp = pointL.next;          //保存A
                        tmp2 = pointR.next.next;    //保存D
                        pointL.next = pointR.next;  //pre->C
                        pointL.next.next = tmp;     //C->A
                        pointR.next = tmp2;         //B->D
                        pointL = pointL.next;       //后移一位
                        //print(headPointer.next);
                        j--;    //每次进行插入后,进行j--
                    }
                    else{
                        pointL = pointL.next;
                    }
                }
                for(int k=window; k>0; k--){    //将指针移动到下一个windonw内
                     if(null == headPointerTmp.next) break; //这里可以处理非2^n长度的链表
                    headPointerTmp = headPointerTmp.next;
                }

            }

            window = window * 2; //扩大窗口
            headPointerTmp = headPointer;//重新指向最开始
        }
        return headPointer.next; //返回头结点
    }
    public void print(ListNode head){
        ListNode point = head;
        for(int m=length(head); m>0; m--){
            System.out.print(point.val + " ");
            point = point.next;
        }
        System.out.println();
    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(4);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(1);
        ListNode l4 = new ListNode(3);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(-1);
        ListNode l7 = new ListNode(-2);
        ListNode l8 = new ListNode(-100);
        ListNode l9 = new ListNode(-1000);
        ListNode l10 = new ListNode(-1000);
        ListNode k = null;

        ListNode lm = null;
        SortList s = new SortList();

        //k.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = l7;
        l7.next = l8;
        l8.next = l9;
        l9.next = l10;

        lm = s.sortList(l1);
        s.print(lm);
        //System.out.println(lm.val);
        //System.out.println(lm.next.val);

    }
}
时间: 2024-11-10 14:47:31

Sort List 【leetCode】的相关文章

【LeetCode】Sort Colors

LeetCode OJ Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, w

【leetcode】905. Sort Array By Parity

题目如下: 解题思路:本题和[leetcode]75. Sort Colors类似,但是没有要求在输入数组本身修改,所以难度降低了.引入一个新的数组,然后遍历输入数组,如果数组元素是是偶数,插入到新数组头部,否则追加到尾部. 代码如下: class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ res =

【LeetCode】排序 sort(共20题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [56]Merge Intervals [57]Insert Interval [75]Sort Colors [147]Insertion Sort List [148]Sort List [164]Maximum Gap [179]Largest Number [242]Valid Anagram [252]Meeting Rooms (2018年11月22日,为

【题解】【数组】【Leetcode】Median of Two Sorted Arrays

Median of Two Sorted Arrays There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

【LeetCode】Subsets II 解题报告

[题目] Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solutio

【LeetCode】数组--合并区间(56)

写在前面   老粉丝可能知道现阶段的LeetCode刷题将按照某一个特定的专题进行,之前的[贪心算法]已经结束,虽然只有三个题却包含了简单,中等,困难这三个维度,今天介绍的是第二个专题[数组] 数组(Array)是一种线性表数据结构.它用一组连续的内存空间,来存储一组具有相同类型的数据.在每一种编程语言中,基本都会有数组这种数据类型.不过,它不仅仅是一种编程语言中的数据类型,还是一种最基础的数据结构. 贪心算法回顾: [LeetCode]贪心算法--买卖股票的最佳时机II(122) [LeetC

【leetcode】893. Groups of Special-Equivalent Strings

Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-of-special-equivalent-strings/ 1)problem You are given an array A of strings. Two strings S and T are special-equivalent if after any number of moves,

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"