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
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
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
相关文章推荐
- leetcode-56&88 Merge Intervals && Merge Sorted Array
- LeetCode 88:Merge Sorted Array
- 【leetcode c++】88 Merge Sorted Array
- <LeetCode OJ> Merge Sorted Array【88】
- LeetCode(88)Merge Sorted Array
- 88 Merge Sorted Array
- 88. Merge Sorted Array
- 88. Merge Sorted Array
- <LeetCode><Easy> 88 Merge Sorted Array
- leetcode 88:Merge Sorted Array
- [LeetCode]88 Merge Sorted Array
- LeetCode - 21/23/88 - Merge Sorted Lists/Array
- 88. Merge Sorted Array
- [LeetCode-88] Merge Sorted Array(合并有序数组)
- LeetCode 88 — Merge Sorted Array(C++ Java Python)
- 88. Merge Sorted Array
- 88. Merge Sorted Array
- (java)leetcode-88:Merge Sorted Array
- LeetCode@Array_88_MergeSortedArray
- 88. Merge Sorted Array LeetCode