Skip to content

Commit 51bbc48

Browse files
author
applewjg
committed
MergeSortedArray
Change-Id: I47cac0a413ef4415ecc6c92d4ddadf96823ab782
1 parent d514441 commit 51bbc48

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

MergeSortedArray.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
Author: Andy, [email protected]
3+
Date: Jan 7, 2015
4+
Problem: Merge Sorted Array
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/merge-sorted-array/
7+
Notes:
8+
Given two sorted integer arrays A and B, merge B into A as one sorted array.
9+
Note:
10+
You may assume that A has enough space to hold additional elements from B.
11+
The number of elements initialized in A and B are m and n respectively.
12+
13+
Solution: From back to forth.
14+
*/
15+
16+
public class Solution {
17+
public void merge(int A[], int m, int B[], int n) {
18+
int i = m - 1;
19+
int j = n - 1;
20+
int x = m + n - 1;
21+
while (i >= 0 && j >= 0)
22+
if (A[i] >= B[j]) A[x--] = A[i--];
23+
else A[x--] = B[j--];
24+
while (j >= 0) A[x--] = B[j--];
25+
}
26+
}

0 commit comments

Comments
 (0)