前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode]Merge Sorted Array 合并排序数组 [LeetCode]Merge Sorted Array 合并排序数组

[LeetCode]Merge Sorted Array 合并排序数组 [LeetCode]Merge Sorted Array 合并排序数组

作者头像
尾尾部落
发布2018-09-04 13:47:29
4360
发布2018-09-04 13:47:29
举报
文章被收录于专栏:尾尾部落

链接:https://leetcode.com/problems/merge-sorted-array/description/ 难度:Easy 题目:88. 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和nums2,将nums2按顺序合并到nums1(从小到大)。 提示:假设nums1有足够的空间(大小大于或等于m + n)来保存nums2中的其他元素。

思路:A和B都已经是排好序的数组,我们只需要从后往前比较就可以了。因为A有足够的空间容纳A + B,我们使用游标i指向m + n – 1,也就是最大数值存放的地方,从后往前遍历A,B,谁大就放到i这里,同时递减i。

参考代码: Java

代码语言:javascript
复制
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        for(int i=m + n - 1; i>=0 ; i--){
            if(m>0 && n>0){
                if(nums1[m-1]>nums2[n-1]){
                    nums1[i] = nums1[m-1];
                    m --;
                }else{
                    nums1[i] = nums2[n-1];
                    n --;
                }
            }else if(m<=0){
                nums1[i] = nums2[n-1];
                n --;
            }else if(n<=0){
                nums1[i] = nums1[m-1];
                m --;
            }      
        }
    }
}		
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档