LeetCode-Merge Sorted Array

Description:
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]

题意:给定两个已排序的数组,要求将第二个数字添加到第一个数组中,并且保证此时的第一个数组也是有序的;

解法:这道题其实就是一个对数组的排序问题,我们将第二个数组接在第一个数组的尾部,因为第一个数组已经是有序的了,通过选择排序算法,我们从第二个数组的位置开始使用此算法;

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        for(int i=0; i<n; i++){
            nums1[i+m] = nums2[i];
        }//第二个数组拼接在第一个数组的尾部
        for(int i=m; i<m+n; i++){
            for(int j=i; j>0; j--){
                if(nums1[j] < nums1[j-1]){
                    int temp = nums1[j];
                    nums1[j] = nums1[j-1];
                    nums1[j-1] = temp;
                }//交换前后两个数字
                else{
                    break;
                }
            }
        }//选择插入排序
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80925130