合并两个有序数组
(easy,1过)
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
- 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
- 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6]
需要注意:
1.归并排序最后一步,避免数组移动需要从后往前遍历
2.要考虑A遍历完B有剩余情况,需要额外把B中元素插入A前部
public void merge(int A[], int m, int B[], int n) { int index = m+n-1; int indexA = m-1; int indexB = n-1; while (index >= 0 && indexA >= 0 && indexB >= 0) { if (A[indexA] > B[indexB]) { A[index] = A[indexA]; index--; indexA--; } else { A[index] = B[indexB]; index--; indexB--; } } if (indexB >= 0) { while (index >=0 && indexB>=0) { A[index] = B[indexB]; index--; indexB--; } } }
合并两个有序链表(easy)
(1 pass)
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode res = new ListNode(0); ListNode cur = res; while(l1 != null && l2 != null) { if (l1.val < l2.val) { cur.next = l1; cur = cur.next; l1 = l1.next; } else { cur.next = l2; cur = cur.next; l2 = l2.next; } } if (l1 ==null) { cur.next = l2; } else { cur.next = l1; } return res.next; }