您的位置:首页 > 其它

LeetCode88 Merge two sort array

2017-04-18 21:53 381 查看

description

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 nums1 and nums2 are m and n respectively.


这道题目与干才写的一道题目类似,只不过这个是在leetcode上的题目,没有使用java中自带的方法来实现所要的功能,是使用的不断取小的方式来进行处理

public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (nums2 == null || nums2.length == 0) {
return;
}
int[] arr = new int[m + n];
int i = 0, j = 0, count = 0;
while (i < m && j < n) {
if (nums1[i] < nums2[j]) {
arr[count++] = nums1[i++];
} else {
arr[count++] = nums2[j++];
}
}
while(i < m) {
arr[count++] = nums1[i++];
}
while(j < n) {
arr[count++] = nums2[j++];
}
System.arraycopy(arr, 0, nums1, 0, n + m);
}
}


updata

从后向前寻找数组,直到找到所用的数据;

该方法的时间复杂度、空间复杂度更低。

class Solution {
/**
* @param A: sorted integer array A which has m elements,
*           but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
if (B == null || B.length == 0) {
return;
}
int i = m - 1, j = n - 1, count = m + n - 1;
while (i >= 0 && j >= 0) {
if (A[i] > B[j]) {
A[count--] = A[i--];
} else {
A[count--] = B[j--];
}
}
while (i >= 0) {
A[count--] = A[i--];
}
while (j >= 0) {
A[count--] = B[j--];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: