LeetCode(088) Merge Sorted Array(Java)

来源:互联网 发布:软件定义世界 编辑:程序博客网 时间:2024/04/30 19:39

题目如下:

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.


分析如下:

数组A:  {11111.........}

数组B:  {2222}

A' (A after merge) = A + B , 因为 A 在题目中保证了有足够多的空间。

必然按照index从大到小的顺序进行merge,才不会把A的元素给抹掉。


我的代码:

//245mspublic class Solution {    public void merge(int A[], int m, int B[], int n) {        int j = m - 1;        int k = n - 1;        for (int i = m + n - 1; i >=0; --i) {            if (j >=0 && k >= 0) {                if (A[j] > B[k]) {                    A[i] = A[j];                    --j;                } else {                    A[i] = B[k];                    --k;                }            } else if (j >=0) {                 A[i] = A[j];                --j;            } else if (k >=0) {                A[i] = B[k];                --k;            }        }    }}


0 0
原创粉丝点击