zoukankan      html  css  js  c++  java
  • Merge Sorted Array

    Given two sorted integer arrays A and B, merge B into A as one sorted array.

    Note:
    You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.

     解法一:

    public class Solution {
        public void merge(int A[], int m, int B[], int n) {
            if(m==0){
                for(int i=0;i<n;i++){
                    A[i] = B[i];
                }
                return;
            }
            if(n==0) return;
            int[] C = new int[m+n];//new一个大小为m+n的数组
            int a = 0,b = 0,c = 0;//三个下标
            while(a<m&&b<n){
                if(A[a]<B[b]){
                    C[c++] = A[a];
                    if(a==m-1){
                        while(b<n){
                            C[c++] = B[b++];//A数组遍历结束,将B数组剩下元素顺序复制到C数组
                        }
                        break;
                    }
                    else{
                        a++;
                    }
                }
                else{
                    C[c++] = B[b];
                    if(b==n-1){
                        while(a<m){
                            C[c++] = A[a++];//B数组遍历结束,将A数组剩下元素顺序复制到C数组
                        }
                        break;
                    }
                    else{
                        b++;
                    }
                }
            }
            int k = 0;
            while(k<m+n){
                A[k] = C[k];
                k++;
            }
        }
    }

    解法二:从后往前考虑,将2个数组中较大的存放在m+n-i位置处,i初始为1;这样每个元素存放的位置就是其最终位置,代码如下:

    public class Solution {
        public void merge(int A[], int m, int B[], int n) {
           int i = m+n-1;
           int a = m-1;
           int b = n-1;
           while(a>=0&&b>=0) {
               if(A[a]>B[b]) A[i--] = A[a--];
               else A[i--] = B[b--];
           }
           while(b>=0){
               A[i--] = B[b--];
           }
        }
    }
  • 相关阅读:
    C艹目录
    C艹重复输入小方法,for循环+while
    python with 语句妙用
    python with妙用
    Kali配置网卡静态信息
    Spring 之 注解详解
    html基础之 表单提交方法
    html 基础之 <link>标签
    android:padding和android:margin的区别
    css基础之 font的简写规则 以及 自定义 CSS3 @font-face详细用法
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4274831.html
Copyright © 2011-2022 走看看