您的位置:首页 > 编程语言 > Go语言

Merge Sorted Array

2014-02-01 02:53 197 查看


Merge Sorted Array

 Total Accepted: 6782 Total
Submissions: 21148My Submissions

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

You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

public static void merge2(int[] A, int m, int[] B, int n) {
int i = m + n - 1;
m--;n--;
while (m >= 0 && n >= 0) A[i--] = A[m] > B
? A[m--] : B[n--];
while (n >= 0) A[i--] = B[n--];
}

或者:
public static void merge(int[] A, int m, int[] B, int n) {
System.arraycopy(A, 0, A, n, m);
int a = n, b = 0, i = 0;
while (a < m + n && b < n) A[i++] = A[a] <= B[b] ? A[a++] : B[b++];
while (b < n) A[i++] = B[b++];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode