您的位置:首页 > 其它

88. Merge Sorted Array

2017-10-15 15:27 225 查看
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.

java

class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return;
}
int index = m + n - 1;
n -= 1; m -= 1;
while (m >= 0 && n >= 0) {
if (nums1[m] > nums2
) {
nums1[index] = nums1[m];
m -= 1;
} else {
nums1[index] = nums2
;
n -= 1;
}
index -= 1;
}
while (n >= 0) {
nums1[index--] = nums2[n--];
}
}
}


python

class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if nums1 == None or nums2 == None or n == 0:
return
index, m, n = m + n - 1, m - 1, n - 1
while m >= 0 and n >= 0:
if nums1[m] > nums2
:
nums1[index] = nums1[m]
m -= 1
else:
nums1[index] = nums2

n -= 1
index -= 1
while n >= 0:
nums1[index] = nums2

index, n = index - 1, n - 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: