问题描述:You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
算法分析:合并两个数组,但是合并后的数组是原来的数组1,不能新建空间,假设数组1有足够的空间,从后往前遍历,避免覆盖问题。同类问题还有合并两个有序的链表,链表和数组的问题都相似。
//从后往前遍历比较,不会遇到覆盖的问题 public class MergeSortedArray { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m-1, j = n-1; int z = m+n-1; while(i >= 0 && j >= 0) { if(nums1[i] > nums2[j]) { nums1[z--] = nums1[i--]; } else { nums1[z--] = nums2[j--]; } } if(i < 0) { for(int k = j; k >= 0; k --) { nums1[z--] = nums2[k]; } } } }
合并两个有序链表:
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dumy = new ListNode(0); ListNode head = dumy; while(l1 != null && l2 != null) { if(l1.val < l2.val) { dumy.next = l1; l1 = l1.next; } else { dumy.next = l2; l2 = l2.next; } dumy = dumy.next; } if(l1 == null) { dumy.next = l2; } if(l2 == null) { dumy.next = l1; } return head.next; } }
时间: 2024-10-12 22:41:25