zoukankan      html  css  js  c++  java
  • 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--];
            
        }
    }
    不积跬步无以至千里,千里之堤毁于蚁穴。 你是点滴积累成就你,你的丝丝懒惰毁掉你。 与诸君共勉
  • 相关阅读:
    openCV学习——一、图像读取、显示、输出
    caffe配置文件
    5.卷积神经网络
    【caffe】基本数据结构blob
    URLSearchParams对象
    window.history对象
    在React项目中添加ESLint
    memorization-根据输入重新计算render的数据
    React重置非受控组件state的方法
    彻底搞清楚DOM元素的height,offsetHeight,clientHeight,scrollHeight
  • 原文地址:https://www.cnblogs.com/haoHaoStudyShare/p/7353631.html
Copyright © 2011-2022 走看看