88 Merge Sorted Array

本文介绍了一种将两个已排序的整数数组合并为一个有序数组的方法。通过从后向前比较两个数组中的元素,直接在目标数组中填充较大的值,避免了不必要的元素移动。此方法无需额外空间,适用于LeetCode上的一道经典题目。

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

题目:

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.

解题思路:
这题是有序数组的归并。技巧在于,归并时从后往前归并。
若从前往后,就需要挪动 nums1 中原有的元素。也不需要额外的空间暂存排好序的元素。

代码实现:

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if(nums1 == null || nums1.length == 0) {
            if(nums2 != null && nums2.length > 0) {
                Arrays.fill(nums1, 0);
                for(int i = 0; i < n; i ++)
                    nums1[i] = nums2[i];
            }
            return;
        }
        if(nums2 == null || nums2.length == 0) {
            if(nums1 != null && nums1.length > 0)
                return;
        }
        int i = m + n - 1;
        int j = m - 1;
        int k = n - 1;
        while(j >= 0 && k >= 0) {
            if(nums1[j] > nums2[k])
                nums1[i --] = nums1[j --];
            else if(nums1[j] < nums2[k])
                nums1[i --] = nums2[k --];
            else {
                nums1[i --] = nums1[j --];
                nums1[i --] = nums2[k --];
            }
        }
        while(j >= 0)
            nums1[i --] = nums1[j --];
        while(k >= 0)
            nums1[i --] = nums2[k --];
        return;
    }
}
59 / 59 test cases passed.
Status: Accepted
Runtime: 0 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值