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.

    从后往前遍历,减少移动次数。此题与替换字符串类似

     1 public void merge(int A[], int m, int B[], int n) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int k = m + n - 1;
     5         int aIdx = m - 1, bIdx = n - 1;
     6         while(aIdx >= 0 && bIdx >= 0){
     7             if(A[aIdx] >= B[bIdx]){
     8                 A[k] = A[aIdx];
     9                 aIdx --;
    10             } else {
    11                 A[k] = B[bIdx];
    12                 bIdx --;
    13             }
    14             k --;
    15         }
    16         
    17         while(bIdx >= 0){
    18             A[k] = B[bIdx];
    19             bIdx --;
    20             k --;
    21         }
    22     }
  • 相关阅读:
    多线程 介绍
    AE中如何获取曲线的一部分(转)
    friday
    THU
    MON
    SAT
    周三
    TUE
    绝对遗憾!
    monday
  • 原文地址:https://www.cnblogs.com/feiling/p/3239260.html
Copyright © 2011-2022 走看看