zoukankan      html  css  js  c++  java
  • [LeetCode]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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

    思考:3指针。从后往前遍历。

    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int i=m-1;
            int j=n-1;
            int k=m+n-1;
            while(k>=0)
            {
                if(i>=0&&A[i]>=B[j]) 
                {
                    A[k]=A[i];
                    i--;
                    k--;
                }
                else if(j>=0&&A[i]<B[j])
                {
                    A[k]=B[j];
                    j--;
                    k--;
                }
                if(i>=0&&j<0) return;
                if(i<0&&j>=0)
                {
                    for(int p=0;p<=j;p++)
                    {
                        A[p]=B[p];
                    }
                    return;
                }
            }
        }
    };
    

    2014-03-27 16:53:19

    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int i=m-1;
            int j=n-1;
            int k=m+n-1;
            while(i>=0&&j>=0)
            {
                if(A[i]>B[j]) A[k--]=A[i--];
                else A[k--]=B[j--];
            }
            //未考虑m=0的情况
            while(j>=0) A[k--]=B[j--];
        }
    };
    

      

     

  • 相关阅读:
    js 数组去重的几种方式及原理
    js replace
    gulp的使用方法
    gulp 安装部署
    gulp 的5个方法
    fiddler 监听手机的http请求
    vsCood
    browser-sync使用方法
    browser-sync 安装
    npm 移除第三方包
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3465714.html
Copyright © 2011-2022 走看看