Leetcode OJ 88 Merge Sorted Array [Easy]

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值