您的位置:首页 > 其它

【LeetCode】Merge Sorted Array

2014-03-07 10:15 302 查看
Merge Sorted Array

Total Accepted: 9111 Total Submissions: 28906 My 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 (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.

合并两个排序数组,典型题。这个需要从B合并到A,如果不声明新的空间的话,需要考虑到交换数据,操作起来反而麻烦些。不妨设置新的数组,将值赋给临时空间。这样就转为一般的合并题了。没什么难度,但是很需要基本功。

Java AC

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