LeetCode: Merge Sorted Array

原创 2016年08月31日 00:17:51

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.


Source Code:

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        
        vector<int> res;
        
        int len1 = nums1.size();
        if (len1 > m) { len1 = m; };
        int len2 = nums2.size();
        if (len2 > n) { len2 = n; };
        int i = 0, j = 0;
        while(i < len1 && j < len2) {
            if (nums1[i] < nums2[j]) {
                res.push_back(nums1[i++]);
            }
            else {
                res.push_back(nums2[j++]);
            }
        }
        
        while (i < len1) {
            res.push_back(nums1[i++]);
        }
        while (j < len2) {
            res.push_back(nums2[j++]);
        }
        
        nums1 = res;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

(数组)leetcode 88:Merge Sorted Array

(数组)leetcode 88:Merge Sorted Array

LeetCode 之 Merge Sorted Array

原题: Given two sorted integer arrays A and B, merge B into A as one sorted array. 合并两个有序的数列前面有一个是链表...

LeetCode 88. Merge Sorted Array 归并的过程

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 题意:对于...

[LeetCode]--88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.Note: Y...

[leetcode]88. Merge Sorted Array (java)

题目描述: Merge two sorted linked lists and return it as a new list. The new list should be made by sp...

Leetcode 88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.Note: Y...

LeetCode 88 — Merge Sorted Array(C++ Java Python)

题目:http://oj.leetcode.com/problems/merge-sorted-array/ Given two sorted integer arrays A and B, mer...

LeetCode题解:Merge Sorted Array

题目链接: merge-sorted-array 题目描述: Give two sorted integer arrays nums1 and nums2. merge nums2...

leetcode88---Merge Sorted Array(合并有序数组)

问题描述:Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.Not...

leetcode笔记:Merge Sorted Array

Merge Sorted Array这道题没有很复杂的算法,只是一个技巧问题。如果单纯得考虑从小到大地将两个数组进行合并的话,每次在num1中插入一个数的话,需要将后面的元素都向后移动一位,这样,整个...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)