#6 Merge Two Sorted Arrays

原创 2016年08月30日 13:18:27

题目描述:

Merge two given sorted integer array A and B into a new sorted integer array.

Example

A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]


题目思路:

two pointers的简单题,就不多说了。

Mycode(AC = 13ms):

class Solution {
public:
    /**
     * @param A and B: sorted integer array A and B.
     * @return: A new sorted integer array
     */
    vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
        // write your code here
        vector<int> ans(A.size() + B.size(), 0);
        
        if (A.size() == 0) return ans;
        
        int idx1 = 0, idx2 = 0, idx = 0;
        
        while (idx1 < A.size() && idx2 < B.size()) {
            if (A[idx1] <= B[idx2]) {
                ans[idx++] = A[idx1++];
            }
            else {
                ans[idx++] = B[idx2++];
            }
        }
        
        while (idx1 < A.size()) {
            ans[idx++] = A[idx1++];
        }
        
        while (idx2 < B.size()) {
            ans[idx++] = B[idx2++];
        }
        
        return ans;
    }
};


版权声明:三千微尘里,吾宁爱与憎

相关文章推荐

LeetCode4/88 Median of Two Sorted Arrays/Merge Sorted Array

题目地址:https://leetcode.com/problems/median-of-two-sorted-arrays/ 这道题就是求两个有序序列的中位数。这也是2015年4月阿里实习生招人附加...

4_Median_of_Two_Sorted_Arrays

LeetCode 4, 2016-11-12

Median of Two Sorted Arrays C++

这道题目很多人认为是leetcode上最经典的题目之一,很早之前就见过这个题目,好像算法导论也有讲过这个题。题意是找两个排好序的数组的中位数,如果不去考虑时间空间复杂度,这个问题极其简单,用merge...

LeetCode(4)Median of Two Sorted Arrays

题目There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the t...
  • fly_yr
  • fly_yr
  • 2015年08月22日 20:35
  • 1051

Median of Two Sorted Arrays问题及解法

问题描述: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of ...

Java实现Median of Two Sorted Arrays

求两个有序数据的中位数;Java实现Median of Two Sorted Arrays

每日算法之二:Median of Two Sorted Arrays

题目要求如下: There are two sorted arrays A and B of size m and n respectively. Find the median of the two...
  • yapian8
  • yapian8
  • 2014年03月29日 16:43
  • 773

[leetcode]median of two sorted arrays【寻找第k小的数问题】

Median of Two Sorted ArraysThere are two sorted arrays nums1 and nums2 of size m and n respectively....

Median of Two Sorted Arrays(OO)

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted ...

Leetcode刷题记—— 4. Median of Two Sorted Arrays(两有序数组的中位数)

一、题目叙述: There are two sorted arrays nums1 and nums2 of size m...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:#6 Merge Two Sorted Arrays
举报原因:
原因补充:

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