leetcodeのインタビューの質問10.01。ソートマージLCCIマージソートダブルポインタ配列
leetcode 2020年3月の毎日の質問パンチ
プログラマのインタビューゴールデン
タイトル:配列AとBが与えられると、端末AはBを収容するのに十分なバッファ空間である二つのソート ソート組み込まA及びBの調製のための方法。要素AとBの数を初期化し、mおよびnは。
例:
入力:
A = [1,2,3,0,0,0]、M 3 =
B = [2,5,6]、N- = 3。
出力:[1,2,2,3,5,6 ]
説明:A.length == N + M
出典:滞在ボタン(LeetCode)
オリジナルタイトルリンクします。https://leetcode-cn.com/problems/sorted-merge-lcci
アイデア: Pythonの:最も簡単な方法は、Aを並べ替え、A、Bを配置することです 第二の方法は、AとBの使用は、使用条件にソートされていますダブルポインタ。
詳細:この質問は、戻り値はANSので、Aにディープコピーする必要があり、配列Aの配列である:A [:] = ANS
コード:
class Solution(object):
def merge(self, A, m, B, n):
"""
:type A: List[int]
:type m: int
:type B: List[int]
:type n: int
:rtype: None Do not return anything, modify A in-place instead.
"""
# 双指针
pa=0
pb=0
ans=[]
while not(pa==m and pb==n):
if pa == m:
ans.append(B[pb])
pb+=1
continue
if pb == n:
ans.append(A[pa])
pa+=1
continue
if A[pa]>B[pb]:
ans.append(B[pb])
pb+=1
continue
if A[pa]<B[pb]:
ans.append(A[pa])
pa+=1
continue
if A[pa]==B[pb]:
ans.append(A[pa])
ans.append(B[pb])
pa+=1
pb+=1
continue
A[:]=ans
return A
このブログは、オリジナル作品である指針を歓迎し、再現し、ソースを示し、この記事へのリンクを添付し、あなたに感謝して下さい