[leetcode]Merge Sorted Array

简单题。从尾巴开始往前就行了。

public class Solution {

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

        // Start typing your Java solution below

        // DO NOT write main() function

        int len = m + n;

        int i = m - 1;

        int j = n - 1;

        int k = len - 1;

        

        while (i >= 0 && j >= 0) {           

            if (A[i] >= B[j]) {

                A[k] = A[i];

                i--;

            } else {

                A[k] = B[j];

                j--;

            }

            

            k--;

        }

        

        int idx = i >= 0 ? i : j;

        int[] tmp = i >=0 ? A : B;

        while (idx >=0) {

            A[k] = tmp[idx];

            k--;

            idx--;

        }

    }

}

 

你可能感兴趣的:(LeetCode)