Leetcode 88. Merge Sorted Array

来源:互联网 发布:安装ubuntu与win7共存 编辑:程序博客网 时间:2024/05/21 10:51

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.

s思路:
1. 这道题考察啥呢?说到底,是对边界的理解和重视。两个sorted array要合并,简单粗暴的方法就是:nums1和nums2每个数比较,如果nums2的数在nums1两个数中间,则把nums2的数插入nums1中,这一插入,就导致vector的后面数移位,复杂度就高了,移位不要紧,关键是移位以后nums1中的坐标就发生变化。麻烦的是,如果nums2的数大于nums1的最后一个数,则nums2后面的所有数都直接添加在nums1后面。因此,讨论的情况也很多。
2. 现在基本有这么一个意识了:看到思路考虑的情况太多太复杂,肯定是思考的角度和方式不正确。而且,一般都是从相反的角度思考一下,问题就立马简单起来。比如:这个题,不从左边比较,从右边比较:num1和num2尾巴上的数谁大就把谁放在nums1的i+j的位置上,然后位置往前移动。
这里写图片描述

调试:
1. 把nums2插入nums1,所以while条件就是nums2插入完全,所以不需要用l来做条件
2. 因为坐标i要做运算,而且i可能小于0,如果m=0。所以要加保护!

class Solution {public:    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {        //        int l=m+n-1;        int i=m-1,j=n-1;        while(j>=0){            nums1[l--]=(i>=0&&nums1[i]>nums2[j])?nums1[i--]:nums2[j--];//考虑极端边界情况:j<0或i<0怎么保护?            }    }};
0 0