Leetcode排序题

博客围绕排序算法展开,包含将有序数组 B 合并到有序数组 A 的操作,还介绍了用插入排序对链表排序,以及要求时间复杂度为 O(n log n)、空间复杂度为常数的链表归并排序,另外有数组的快速排序升序示例,均给出了 Java 或 C++ 代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]
给两个有序的数组 A 和 B,把 B 合并到 A,变成一个数组,假定 A 有足够的空间。

JAVA

class Solution {
    public void merge(int A[] , int m, int B[] , int n) {
        int i = m - 1;
        int j = n - 1;
        int k = m + n - 1;
        while (k >= 0) {
        if (j < 0 || (i >= 0 && A[i] > B[j]))
            A[k--] = A[i--];
        else
            A[k--] = B[j--];
      }
   }
}

C++

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
       if(n==0)
       {
           return;
       }
        int index=m+n-1;
        int i=m-1;
        int j=n-1;
        while(i>=0 && j>=0)
        {
            if(nums1[i]>nums2[j])
            {
                nums1[index--]=nums1[i--];
            }
            else
            {
                nums1[index--]=nums2[j--];
            }
        }
        if(i==-1)
        {
            while(j>=0)
            {
                nums1[j]=nums2[j];
                j--;
            }
        }
    }
};

147. Insertion Sort List
Sort a linked list using insertion sort.
在这里插入图片描述
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Example 1:

Input: 4->2->1->3
Output: 1->2->3->4
Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

用插入排序方法对链表进行排序。
创建一个辅助的新链表,并且使用一个指针遍历原链表,每次将原链表中的一个节点插入到新链表的合适位置(即该节点的值大于新链表上的节点的值,又小于后一节点的值)。最后将新链表的头部返回即可。
JAVA

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        //创造一个新链表的头部
        ListNode dummy=new ListNode(0);
        //用一个临时变量保持头结点
        ListNode pre=dummy;
        //cur是原链表的指针
        ListNode cur=head;
       while (cur != null) {
            //每次循环前重置pre为头结点,这样保证每次都从头往后遍历
			pre = dummy;
			// 从伪头结点的下一个结点开始,(注意判空)
			// 让pre指向小于cur.val的最大结点(升序)
			while (pre.next != null && pre.next.val < cur.val) {
			pre = pre.next;
        }
        // next暂存cur的下一个结点
			ListNode next = cur.next;
			// 把cur连接在pre后面
			// cur.next指向pre.next
			cur.next = pre.next;
			pre.next = cur;
           //cur指针后移一位
			cur = next;
    }
    return dummy.next;
   }
}

148. Sort List

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4
Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5
要求:1)时间复杂度为O(nlogn);2)空间复杂度为常数,即不能增设额外的空间。
归并排序
JAVA

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        //使用快慢指针查找中间结点
        ListNode fast=head;
        ListNode slow=head;
        while(fast.next!=null)
        {
            fast=fast.next.next;
            //让show少走一步,结点数目均匀
            if(fast==null)
                break;
            slow=slow.next;
        }
        ListNode right=slow.next;
        //注意断裂
        slow.next=null;
        ListNode left=sortList(head);
        right=sortList(right);
        return mergeTwoLists(left,right);
    }
    //递归实现链表排序
    public ListNode mergeTwoLists(ListNode l1,ListNode l2)
    {
        ListNode res=null;
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        if(l1.val<=l2.val)
        {
            res=l1;
            l1.next=mergeTwoLists(l1.next,l2);
        }
        else
        {
            res=l2;
            l2.next=mergeTwoLists(l1,l2.next);
        }
        return res;
    }
}

JAVA2

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        //使用快慢指针查找中间结点
        ListNode fast=head;
        ListNode slow=head;
        while(fast.next!=null)
        {
            fast=fast.next.next;
            //让show少走一步,结点数目均匀
            if(fast==null)
                break;
            slow=slow.next;
        }
        ListNode right=slow.next;
        //注意断裂
        slow.next=null;
        ListNode left=sortList(head);
        right=sortList(right);
        return mergeTwoLists(left,right);
    }
    //递归实现链表排序
    public ListNode mergeTwoLists(ListNode l1,ListNode l2)
    {
        //ListNode res=null;
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        if(l1.val<=l2.val)
        {
            //res=l1;
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }
        else
        {
           // res=l2;
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
       // return res;
    }
}

912. Sort an Array
Given an array of integers nums, sort the array in ascending order.

Example 1:

Input: [5,2,3,1]
Output: [1,2,3,5]
Example 2:

Input: [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
快速排序 升序
JAVA

class Solution {
    
    public int[] sortArray(int[] nums) {
        shuffle(nums);//避免最坏情况
        sortArray(nums,0,nums.length-1);
        return nums;
    }
    
    private void sortArray(int[] nums,int low,int high){
        if(low>=high) return;
        int j = patrition(nums,low,high);//nums[j]已经在合适的位置上了
        sortArray(nums,low,j-1);
        sortArray(nums,j+1,high);
    }
    
    private int patrition(int[] nums,int low,int high){
        int i = low;
        int j = high+1;
        while(true){
            while(nums[++i]<nums[low]){
                if(i==high) break;
            }
            while(nums[--j]>nums[low]){
 
            }
 
            if(i>=j) break;
 
            swap(nums,i,j);   
        }
        swap(nums,low,j);
        return j;
    }
    
    private void shuffle(int[] nums){
        Random random = new Random();
        for(int i = 1;i<nums.length;i++){
            int r = random.nextInt(i+1);
            swap(nums,r,i);
        }
    }
    
    private void swap(int[] nums,int i ,int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值