Leetcode: Merge Sorted Array

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.

这种题都采用倒序的方式吧,从大到小添加。要注意的是一些小细节:比如for(int i = m+n-1; i >=0; i--){}, 在for语句里面已经有i--了,循环里面就不需要再写一个i--了

 1 public class Solution {

 2     public void merge(int A[], int m, int B[], int n) {

 3         int j = m - 1, k = n - 1;

 4         for (int i = m+n-1; i >= 0; i--) {

 5             if (j >= 0 && k >= 0){

 6                 if (A[j] >= B[k]) {

 7                     A[i] = A[j];

 8                     j--;

 9                 }

10                 else {

11                     A[i] = B[k];

12                     k--;

13                 }

14             }

15             else if (k >= 0) {

16                 A[i] = B[k];

17                 k--;

18             }

19         }

20     }

21 }

 

你可能感兴趣的:(LeetCode)