LeetCode小白菜笔记[21]:Merge Sorted Array
2018-02-13 11:59
483 查看
LeetCode小白菜笔记[21]:Merge Sorted Array
88. Merge Sorted Array [easy]
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.
之前有过一道merge sorted lists 的题目,用链表实现有序数列。当时那道题目可以利用直接方法,也可以利用递归求解。
此题相当于上面说的那道题目的array的实现,做法不同。关键在于原位操作,in place,所以就不能直接像list那样从前向后比较,因为每次插入一个新的都要花费较长时间移动后面的元素。所以我们考虑如何插入数值而不移动其他元素? 之所以要在插入数值的时候移动元素,是因为后面有已经存放的数据,那么我们将nums1视为一个长度为m+n的,后面n个为空的长数组,那么如果从后面向前比较并放置元素的话,和从前往后结果一样,但是由于后面是空的,往里面放值不影响前面的已经排好序的已知数值,所以不需要移动操作。按照这个思路,写代码如下:
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. """ while m > 0 and n > 0: if nums1[m-1] >= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if n > 0: nums1[:n] = nums2[:n]
这个是discuss区的代码,自己写的每次都是time limit excess。。。
2018年2月13日11:57:51
明天圣瓦伦丁节,后天除夕夜,大后天年初一。
相关文章推荐
- LeetCode小白菜笔记[7]:Merge Two Sorted Lists
- LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
- Leetcode解题笔记-Merge sorted Array
- leetcode笔记:Merge Sorted Array
- LeetCode - 21/23/88 - Merge Sorted Lists/Array
- LeetCode 21.Merge Two Sorted Lists
- LeetCode: Merge Sorted Array
- leetcode 21 -- Merge Two Sorted Lists
- LeetCode之Merge Sorted Array
- LeetCode:Merge Sorted Array
- Leetcode NO.88 Merge Sorted Array
- Merge Sorted Array [LEETCODE]
- Leetcode 88 Merge Sorted Array
- 【Leetcode】21. Merge Two Sorted Lists
- leetcode_Merge Sorted Array
- [leetcode][array][two pointers] Merge Sorted Array
- LeetCode | Merge Sorted Array
- [leetcode]Merge Sorted Array
- [Leetcode]_21 Merge Two Sorted Lists
- leetcode: Merge Sorted Array O(n)解法