标签:
题目:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.
思路:
题意要把两个有序的数组合并到他们中的一个数组中。
唯一的技巧就是从结尾开始归并,不会覆盖元素又能满足题意。
code:
public class Solution { public void merge(int A[], int m, int B[], int n) { while(m > 0 && n > 0) { if(A[m-1] > B[n-1]) { A[m+n-1] = A[m-1]; m--; } else { A[m+n-1] = B[n-1]; n--; } } while(n > 0) { A[m+n-1] = B[n-1]; n--; } while(m > 0) { A[m+n-1] = A[m-1]; m--; } } }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4613429.html