Merge Two Sorted Arrays without additional memory

本文介绍了一种不使用额外内存的方法来合并两个有序数组到较长的数组中,通过从数组末尾开始比较并放置元素的方式实现。示例展示了如何将长度为3的长数组{1,3,5,0,0,0}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创转载请注明出处:http://agilestyle.iteye.com/blog/2361133

 

Question

Merge Two Sorted Arrays into the larger array, given the large array has extra storage. Merge without additional memory

 

Requirements

Long sorted array {1,3,5,0,0,0} (0 means blank spaces), so used length is 3

The short sorted array {2,4}

The expected merged array will be {1,2,3,4,5,0}

Additionally, no additional memory is used

  • e.g. declaring a new array is not allowed

Solution

1. Loop from end to beginning.

2. Keep track of two tail index values of two merged arrays.

3. Final-merged-tail position is equal to longTail+ShortTail+1 (both index start from 0!!)

4. If the shortTail is larger than or equal to 0 after merging, adding the remaining values to the merged array

 

package org.fool.java.test;

public class MergeTwoSortedArrays {
    public static void main(String[] args) {
        int[] longArray = {1, 3, 5, 7, 0, 0, 0, 0};
        int used = 4;
        int[] shortArray = {2, 4, 6};

        for (int i : longArray) {
            System.out.print(i + " ");
        }

        System.out.println();

        merge(longArray, shortArray, used);

        for (int i : longArray) {
            System.out.print(i + " ");
        }
    }

    // we passed 3 arguments, the first 2 are the 2 arrays
    // the longUsed is to present how many items are used in the longArray
    // This method returns a int value representing how many valid items to be counted in the merged long array
    private static int merge(int[] longArray, int[] shortArray, int longUsed) {
        int longTail = longUsed - 1;
        int shortTail = shortArray.length - 1;

        // the order is to merge from end to beginning
        while (longTail >= 0 && shortTail >= 0) {
            // check which one in the two arrays should be put at this current tail position
            if (longArray[longTail] > shortArray[shortTail]) {
                // which means at this position, we'd better to put the value int the longArray for the merged array
                longArray[longTail + shortTail + 1] = longArray[longTail];

                // notice the key here for the final index in the merged array
                // longTail + shortTail + 1 will be the final index, thinking that both tail indexes start from 0

                longTail--; // after we put one value in longArray, we need to shift our focus to the left a little
            } else {
                longArray[longTail + shortTail + 1] = shortArray[shortTail];
                shortTail--;
            }
        }

        // case 1, longTail not equal to 0? No problem, they are in position already
        // case 2, shortTail not equal to 0? Need to add element one by one to the final array
        while (shortTail >= 0) {
            longArray[shortTail] = shortArray[shortTail];   // notice the final merging is same as copying
            shortTail--;    // do not forget updating the index
        }

        // return how many used elements in the new merged array
        return shortArray.length + longUsed;
    }
}

Console Output


 

Reference

https://www.youtube.com/watch?v=zYrlYlwkbLo&list=PLlhDxqlV_-vkak9feCSrnjlrnzzzcopSG&index=40

 

 

 

题目描述是关于寻找两个已排序数组 `nums1` 和 `nums2` 的合并后的中位数。这两个数组分别包含 `m` 和 `n` 个元素。要解决这个问题,首先我们需要合并这两个数组并保持有序,然后根据数组的总大小决定取中间值的方式。 1. 合并两个数组:由于数组是有序的,我们可以使用双指针法,一个指向 `nums1` 的起始位置,另一个指向 `nums2` 的起始位置。比较两个指针所指元素的大小,将较小的那个放入一个新的合并数组中,同时移动对应指针。直到其中一个数组遍历完毕,再将另一个数组剩余的部分直接复制到合并数组中。 2. 计算中位数:如果合并数组的长度为奇数,则中位数就是最中间的那个元素;如果长度为偶数,则中位数是中间两个元素的平均值。我们可以通过检查数组长度的奇偶性来确定这一点。 下面是Python的一个基本解决方案: ```python def findMedianSortedArrays(nums1, nums2): merged = [] i, j = 0, 0 # Merge both arrays while i < len(nums1) and j < len(nums2): if nums1[i] < nums2[j]: merged.append(nums1[i]) i += 1 else: merged.append(nums2[j]) j += 1 # Append remaining elements from longer array while i < len(nums1): merged.append(nums1[i]) i += 1 while j < len(nums2): merged.append(nums2[j]) j += 1 # Calculate median length = len(merged) mid = length // 2 if length % 2 == 0: # If even, return average of middle two elements return (merged[mid - 1] + merged[mid]) / 2.0 else: # If odd, return middle element return merged[mid] ``` 这个函数返回的是两个数组合并后的中位数。注意,这里假设数组 `nums1` 和 `nums2` 都是非空的,并且已经按照升序排列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值