leetcode--Merge Sorted Array

本文介绍了一种有效的合并两个已排序数组的方法,通过从后向前比较并放置元素来保持排序特性,确保了空间效率。

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

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

Note:
You may assume that nums1 has enough space (size that is greater or equal tom + n) to hold additional elements from nums2. The number of elements initialized innums1 and nums2 are m and n respectively.


题意:合并两个排序的数组,要求新数组也是排序的

分类:数组,双指针


解法1:从后向前合并,这样避免了覆盖的问题。

[java]  view plain  copy
  1. public class Solution {  
  2.     public void merge(int[] nums1, int m, int[] nums2, int n) {  
  3.         int len = nums1.length;  
  4.         int index = len-1;  
  5.         int i=m-1,j=n-1;  
  6.         while(i>=0&&j>=0){  
  7.             if(nums1[i]>nums2[j]){  
  8.                 nums1[index] = nums1[i];  
  9.                 i--;  
  10.             }else{  
  11.                 nums1[index] = nums2[j];  
  12.                 j--;  
  13.             }  
  14.             index--;  
  15.         }  
  16.         while(i>=0){  
  17.             nums1[index--]=nums1[i--];  
  18.         }  
  19.         while(j>=0){  
  20.             nums1[index--]=nums2[j--];  
  21.         }  
  22.     }  
  23. }  


[java]  view plain  copy
  1. public class Solution {  
  2.     public void merge(int[] nums1, int m, int[] nums2, int n) {  
  3.         m = m-1;  
  4.         n = n-1;  
  5.         int i=nums1.length-1;  
  6.         for(;m>=0&&n>=0&&i>0;i--){  
  7.             if(nums1[m]>nums2[n]){  
  8.                 nums1[i] = nums1[m];  
  9.                 m--;  
  10.             }else{  
  11.                 nums1[i] = nums2[n];  
  12.                 n--;  
  13.             }  
  14.         }  
  15.         while(m>=0){  
  16.             nums1[i] = nums1[m];  
  17.             m--;i--;  
  18.         }  
  19.         while(n>=0){  
  20.             nums1[i] = nums2[n];  
  21.             n--;i--;  
  22.         }  
  23.     }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46377359

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值