【LeetCode】88.Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]


【解题思路】

算法:归并排序

语言:使用python语言,借用列表的insert和pop操作。注意默认pop是从最后弹出,此题需要设置pop(0)。

【参考代码_44ms】

class Solution:
    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.
        """
        i=0
        count=0
        k=0
        for k in range(n):
            nums1.pop()
        while (count<m and len(nums2)):
            print(i,nums2[0],nums1[i])
            print(len(nums1))
            if (nums2[0]<=nums1[i]):
                nums1.insert(i,nums2[0])
                nums2.pop(0)
                i=i+1
            else:
                i=i+1
                count=count+1
        while(len(nums2)):
            nums1.insert(i,nums2[0])
            i=i+1
            nums2.pop(0)

解此题过程中遇到常见坑:

1、notepad++缩进问题,出问题时及时调出空格符检查是否有缩进问题。

2、考虑边界问题时注意思路清晰,分类讨论。(e.g.nums1先读完 or nums2先读完)

3、还要注意题目要求,新建列表再赋值给nums1是不行滴,因为存储空间已经变了,OJ系统读结果只读nums1内存.

Solution区大神代码:

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int i=m-1;
        int j=n-1;
	int k = m+n-1;
	while(i >=0 && j>=0)
	{
		if(A[i] > B[j])
		    A[k--] = A[i--];
		else
		    A[k--] = B[j--];
	}
	while(j>=0)
	    A[k--] = B[j--];
    }
};

因为给定的列表A长度是m+n,所以将A看做是结果列表,直接从最后(最大元素)开始(这样可以避免从前面开始的各种插入工作),反其道而行之,Please accept my knees.

猜你喜欢

转载自blog.csdn.net/u012509485/article/details/80286109