前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 88 Merge Sorted Array

leetcode 88 Merge Sorted Array

作者头像
流川疯
发布2019-01-18 17:07:44
3360
发布2019-01-18 17:07:44
举报

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.

测试用例:

Runtime Error Message:

Last executed input:

Input:[1,2,3,0,0,0], 3, [2,5,6], 3

Output:[1,2,3,5,6]

Expected:[1,2,2,3,5,6]

错误的解决方案:

代码语言:javascript
复制
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) 
    {
    set<int> result;
    for(int i = 0;i<m;i++)
    {
        result.insert(nums1[i]);
    }
    for(int i = 0;i<n;i++)
    {
        result.insert(nums2[i]);
    }
    nums1.clear();
    set<int>::iterator iter = result.begin();
    for(;iter!=result.end();iter++)
    {
        nums1.push_back(*iter);
    }
    }
};

我的解决方案:上面就是相同 的元素没装进来,换成multiset就行了

代码语言:javascript
复制
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) 
    {
    multiset<int> result;
    for(int i = 0;i<m;i++)
    {
        result.insert(nums1[i]);
    }
    for(int i = 0;i<n;i++)
    {
        result.insert(nums2[i]);
    }
    nums1.clear();
    set<int>::iterator iter = result.begin();
    for(;iter!=result.end();iter++)
    {
        nums1.push_back(*iter);
    }
    }
};

 简短的解决方案:

代码语言:javascript
复制
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int k = m + n;
        while (k-- > 0)
            A[k] = (n == 0 || (m > 0 && A[m-1] > B[n-1])) ?  A[--m] : B[--n];
    }
};

可读性较好:

代码语言:javascript
复制
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int i=m-1;
        int j=n-1;
        int k = m+n-1;
        while(i >=0 && j>=0)
        {
            if(A[i] > B[j])
                A[k--] = A[i--];
            else
                A[k--] = B[j--];
        }
        while(j>=0)
            A[k--] = B[j--];
    }
};

python解决方案:

代码语言:javascript
复制
class Solution:
# @param A  a list of integers
# @param m  an integer, length of A
# @param B  a list of integers
# @param n  an integer, length of B
# @return nothing(void)
def merge(self, A, m, B, n):
    x=A[0:m]
    y=B[0:n]
    x.extend(y)
    x.sort()
    A[0:m+n]=x

python解决方案2:thats why we love python

代码语言:javascript
复制
def merge(self, A, m, B, n):
        A[m:] = B[:n]
        A.sort()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年06月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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