首页 > 编程语言 > 详细

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

时间:2016-04-15 13:44:54      阅读:197      评论:0      收藏:0      [点我收藏+]

题目来源


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 nums1and nums2 are m and n respectively.


题意分析


Input:

  :type nums1: List[int]
  :type m: int
  :type nums2: List[int]
  :type n: int

Output:

        :rtype: void Do not return anything, modify nums1 in-place instead.

Conditions:合并两个sorted的list,注意是将nums2合并进nums1当中,结果也必须是sorted,不返回任何元素。


题目思路

注意到nums1是有足够的空间存储m+n个元素的,所以直接对nums1进行操作就好,选择从数值较大的位置开始选择元素。

备注:如果n小于0了,就不需要继续合并了。


AC代码(Python)


 1 class Solution(object):
 2     def merge(self, nums1, m, nums2, n):
 3         """
 4         :type nums1: List[int]
 5         :type m: int
 6         :type nums2: List[int]
 7         :type n: int
 8         :rtype: void Do not return anything, modify nums1 in-place instead.
 9         """
10         all = m + n - 1
11         m = m - 1
12         n = n - 1
13         while m >= 0 and n >= 0:
14             if nums1[m] > nums2[n]:
15                 nums1[all] = nums1[m]
16                 m = m - 1
17                 all = all - 1
18             else:
19                 nums1[all] = nums2[n]
20                 n = n - 1
21                 all = all - 1
22         while n >= 0:
23             nums1[all] = nums2[n]
24             all = all - 1
25             n = n - 1
26         
27         
28         

 

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

原文:http://www.cnblogs.com/loadofleaf/p/5395089.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!