Merge Sorted Array 混合插入有序数组

来源:互联网 发布:消防工程预算软件 编辑:程序博客网 时间:2024/06/11 11:30

题目:https://leetcode.com/problems/merge-sorted-array/description/

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
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.

题目大意:

混合插入有序数组

解题思路:混合插入有序数组,由于两个数组都是有序的,所有只要按顺序比较大小即可。最先想到的方法是建立一个m+n大小的新数组,然后逐个从A和B数组中取出元素比较,把较小的加入新数组,然后在考虑A数组有剩余和B数组有剩余的两种情况,最后在把新数组的元素重新赋值到A数组中即可。

/** * @param nums1 数组1 * @param m数组1长度 * @param nums2数组2 * @param n数组2长度 */public static void merge(int nums1[], int m, int nums2[], int n) {if (nums1 == null || nums2 == null)return;int idx1 = m - 1;int idx2 = n - 1;int len = m + n - 1;while (idx1 >= 0 && idx2 >= 0) {if (nums1[idx1] > nums2[idx2]) {nums1[len--] = nums1[idx1--];} else {nums1[len--] = nums2[idx2--];}}while (idx2 >= 0) {nums1[len--] = nums2[idx2--];}}



阅读全文
0 0
原创粉丝点击