Leetcode OJ 88 Merge Sorted Array [Easy]

来源:互联网 发布:mysql创建表sql语句 编辑:程序博客网 时间:2024/06/05 15:18

Leetcode OJ 88 Merge Sorted Array

题目描述:

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

Note:

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

题目理解:

给定两个已排序的数组nums1和nums2,将nums2合并到nums1,变成一个排序数组;

其中:假设nums1有足够的空间(即nums1数组的大小 >= m+n),数组中的元素个数已初始化为m和n。

测试用例:

功能测试:nums1中的数子全部小于/大于nums2中的数字;nums1和nums2中的数字大小交叉排列;

特殊输入:两个数组都是空;其中一个数组是空

分析:

1.  如果对nums1从前往后插入合适的数字,将会有大量的移动元素操作;

2.  因此想到对nums1从后往前插入合适的数字(nums2和原始nums1当前最大的数字);

3.  考虑当nums1或nums2的索引小于0的时,选择索引不小于的0的数组中的元素;

4.  当输入中出现空数组时(m == 0或者n==0),可以直接确定nums1,这样可节约运行成本;//在java代码中if(m==0)的语句出现错误?

解答:

public class Solution {    public void merge(int[] nums1, intm, int[]nums2, int n) {        int index1= m-1;        int index2= n-1;        //if(m == 0){nums1 = nums2; return;}        //if(n == 0){nums1 = nums1;return;}        for(int i = m+n-1; i>=0;i--){            if((index1>= 0 &&index2 >= 0 && nums1[index1] >= nums2[index2])|| index2 < 0){                nums1[i] =nums1[index1--];            }            else if((index1>= 0 &&index2 >= 0 && nums1[index1] < nums2[index2])|| index1 < 0){                nums1[i] = nums2[index2--];            }        }        return;    }}


 

 

阅读全文
0 0