合併排序數組

原題

  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.算法

題目大意

  給定兩個排序的數組,將兩個數組進行合併,合併後也是有序的,合併結果存放在nums1中。nums1中有足夠的空間容納nums2。數組

解題思路

  從兩個數組中的最後一個位置開始進行合併,先找兩個數中較大的移動到正的位置,將那個移動的位置值向前移動一個位置,再進行一樣的操做,直到全部的元素處理完。spa

代碼實現

算法實現類.net

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int pa = m - 1;
        int pb = n - 1;
        int index = m + n - 1;

        while (pa >= 0 && pb >= 0) {
            if (A[pa] >= B[pb]) {
                A[index--] = A[pa--];
            } else {
                A[index--] = B[pb--];
            }
        }

        while (pb >= 0) { // 說明pa必定爲0
            A[index--] = B[pb--];
        }

        // 若是pa >= 0,說明[0, pa]尚未進行判斷,由於[0, pa]的數在A中,因此不要移動了
    }
}
相關文章
相關標籤/搜索