2019年11月3日 星期日

Merge Sorted Array


Merge Sorted Array

  • Lintcode : 64 / Leetcode : 88
  • Level : Easy

Problem

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Example
Example 1:

Input:[1, 2, 3] 3  [4,5]  2
Output:[1,2,3,4,5]
Explanation:
After merge, A will be filled as [1, 2, 3, 4, 5]
Example 2:

Input:[1,2,5] 3 [3,4] 2
Output:[1,2,3,4,5]
Explanation:
After merge, A will be filled as [1, 2, 3, 4, 5]
Notice
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n + m)
space: O(1)

Answer

class Solution {
public:

    void mergeSortedArray(int A[], int m, int B[], int n) {
        int len = n + m - 1;
        int indA = m - 1, indB = n - 1;
        while (indA >= 0 && indB >= 0) {
            while (indA >= 0 && indB >= 0 && A[indA] >= B[indB]) {
                A[len--] = A[indA --];
            }
            while (indA >= 0 && indB >= 0 && A[indA] < B[indB]) {
                A[len--] = B[indB--];
            }
        }
        while (indB >= 0) {
            A[len--] = B[indB--];
        }
    }
};
tags: 2pointers

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...