88. Merge Sorted Array [easy] (Python)
3639 ワード
タイトルリンク
https://leetcode.com/problems/merge-sorted-array/
タイトル
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.
タイトル翻訳
2つの秩序整数配列nums 1およびnums 2が与えられ、nums 2をnums 1に結合して秩序配列が得られる.注意:nums 1は、nums 2の要素を格納するのに十分なサイズ(m+n以上)を有すると仮定する.nums 1とnums 2の初期にはそれぞれmとn個の要素がある.
考え方
考え方1
nums 1にマージする場合は、マージ後のnums 1の末尾要素から、各要素の値がどれくらいであるべきかを順番に前に決定します.プログラムには3つのポインタが必要です.
コード#コード#
考え方2
小さなtrickで、2つのポインタだけでいいです.
コード#コード#
PS:初心者はLeetCodeをブラシして、初心者はブログを書いて、書き間違えたり書いたりして、まだ指摘してください.ありがとうございます.転載は以下のことを明記してください.http://blog.csdn.net/coder_orz/article/details/51681144
https://leetcode.com/problems/merge-sorted-array/
タイトル
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.
タイトル翻訳
2つの秩序整数配列nums 1およびnums 2が与えられ、nums 2をnums 1に結合して秩序配列が得られる.注意:nums 1は、nums 2の要素を格納するのに十分なサイズ(m+n以上)を有すると仮定する.nums 1とnums 2の初期にはそれぞれmとn個の要素がある.
考え方
考え方1
nums 1にマージする場合は、マージ後のnums 1の末尾要素から、各要素の値がどれくらいであるべきかを順番に前に決定します.プログラムには3つのポインタが必要です.
コード#コード#
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.
"""
p, q, k = m-1, n-1, m+n-1
while p >= 0 and q >= 0:
if nums1[p] > nums2[q]:
nums1[k] = nums1[p]
p, k = p-1, k-1
else:
nums1[k] = nums2[q]
q, k = q-1, k-1
nums1[:q+1] = nums2[:q+1]
考え方2
小さなtrickで、2つのポインタだけでいいです.
コード#コード#
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.
"""
p, q = m-1, n-1
while p >= 0 and q >= 0:
if nums1[p] > nums2[q]:
nums1[p+q+1] = nums1[p]
p = p-1
else:
nums1[p+q+1] = nums2[q]
q = q-1
nums1[:q+1] = nums2[:q+1]
PS:初心者はLeetCodeをブラシして、初心者はブログを書いて、書き間違えたり書いたりして、まだ指摘してください.ありがとうございます.転載は以下のことを明記してください.http://blog.csdn.net/coder_orz/article/details/51681144