归并有序数组--Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
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.
题意:归并有序数组(和之前的归并有序链表比较),将nums2归并到nums1中,使用一个tmp临时数组进行归并。
1 class Solution:
2 # @param {integer[]} nums1
3 # @param {integer} m
4 # @param {integer[]} nums2
5 # @param {integer} n
6 # @return {void} Do not return anything, modify nums1 in-place instead.
7 def merge(self, nums1, m, nums2, n):
8 tmp=[0 for i in range(m+n)] #将tmp初始化为长度m+n的0数组
9 i=0;j=0;k=0
10 while i<m and j<n:
11 if nums1[i]<=nums2[j]:
12 tmp[k]=nums1[i]
13 i+=1
14 k+=1
15 else:
16 tmp[k]=nums2[j]
17 j+=1
18 k+=1
19 if i==m: #i==m时说明最后一个nums1[m-1]已经收录,此时i才会+1,==m
20 while k<m+n:
21 tmp[k]=nums2[j];k+=1;j+=1
22 else: #当循环停下来的时候,要么i==m,要么j==n(将nums2最后一个数收录)
23 while k<m+n:
24 tmp[k]=nums1[i];k+=1;i+=1
25 for i in range(m+n):
26 nums1[i]=tmp[i] #按照题意,nums2归并到nums1中