您的位置:首页 > 编程语言 > Python开发

[LeetCode]题解(python):088-Merge Sorted Array

2015-12-30 14:11 627 查看
[b]题目来源:[/b]

  https://leetcode.com/problems/merge-sorted-array/

[b]题意分析:[/b]

  给定两个排好序的数组nums1和nums2,将两个数组整合成一个新的排好序的数组,并将这个数组存在nums1里面。

[b]题目思路:[/b]

  由于题目没有要求,所以用一个tmp临时变量将nums1和nums2的数组整合起来,然后将tmp的数赋给nums1就可以了。

[b]代码(Python):[/b]

  

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.
"""
tmp = []
i,j = 0,0
while i < m or j < n:
if i != m and j != n:
if nums1[i] < nums2[j]:
tmp.append(nums1[i]);i += 1
else:
tmp.append(nums2[j]);j += 1
elif i == m:
tmp.append(nums2[j]); j += 1
else:
tmp.append(nums1[i]); i += 1
i = 0
while i < (m + n):
nums1[i] = tmp[i]
i += 1


View Code

转载请注明出处:/article/6365028.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: