LeetCode88 Merge two sort 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.

这道题目与干才写的一道题目类似,只不过这个是在leetcode上的题目,没有使用java中自带的方法来实现所要的功能,是使用的不断取小的方式来进行处理

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if (nums2 == null || nums2.length == 0) {
            return;
        }
        int[] arr = new int[m + n];
        int i = 0, j = 0, count = 0;
        while (i < m && j < n) {
            if (nums1[i] < nums2[j]) {
                arr[count++] = nums1[i++];
            } else {
                arr[count++] = nums2[j++];
            }
        }
        while(i < m) {
            arr[count++] = nums1[i++];
        }
        while(j < n) {
            arr[count++] = nums2[j++];
        }
        System.arraycopy(arr, 0, nums1, 0, n + m);
    }
}

updata

  • 从后向前寻找数组,直到找到所用的数据;
  • 该方法的时间复杂度、空间复杂度更低。
class Solution {
    /**
     * @param A: sorted integer array A which has m elements, 
     *           but size of A is m+n
     * @param B: sorted integer array B which has n elements
     * @return: void
     */
    public void mergeSortedArray(int[] A, int m, int[] B, int n) {
        // write your code here
        if (B == null || B.length == 0) {
            return;
        }
        int i = m - 1, j = n - 1, count = m + n - 1;
        while (i >= 0 && j >= 0) {
            if (A[i] > B[j]) {
                A[count--] = A[i--];
            } else {
                A[count--] = B[j--];
            }
        }
        while (i >= 0) {
            A[count--] = A[i--];
        }
        while (j >= 0) {
            A[count--] = B[j--];
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值