88. Merge Sorted Array【leetcode】算法,java将两个有序数组合并到一个数组中

88. 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 nums1 and nums2 are m and n respectively.

题目:

给定两个排序整数数组A和B,将b合并为一个排序数组。
注意:您可以假设a有足够的空间(大小大于或等于m + n)来保存来自B的附加元素。

分析:

循环递归解决即可,最大的在最后,倒序进行处理

方法1:

 

 1 public class Solution {
 2     public void merge(int[] nums1, int m, int[] nums2, int n) {
 3        // 特别注意这里的m只是nums1中元素的个数,不是最终第一个数组的长度 不要用m=nums1.length;不然会造成数据越界的报错
 4 
 5         int i=m-1,j=n-1,index=m+n-1;
 6     
 7         while(i>=0&&j>=0){
 8             if(nums1[i]>nums2[j]){
 9                 //A大就把A的数组放在更后面
10                 nums1[index--]=nums1[i--];
11               
12             }
13             else{
14                 nums1[index--]=nums2[j--];
15                 
16             }
17         }
18         while(i>=0){
19             //A大就把A的数组放在更后面
20             nums1[index--]=nums1[i--];           
21         }
22         while(j>=0){
23             nums1[index--]=nums2[j--];
24         }
25       
26     }
27 }

 

方法二:三行代码

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

 

转载于:https://www.cnblogs.com/haoHaoStudyShare/p/7353631.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值