【LeetCode-面試演算法經典-Java實現】【088-Merge Sorted Array(合并排序數組)】

來源:互聯網
上載者:User

標籤:歸併排序   演算法   面試   java   

【088-Merge Sorted Array(合并排序數組)】 【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】 原題

  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。

解題思路

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

代碼實現

演算法實作類別

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中,所以不要移動了    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明 歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47290705】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【088-Merge Sorted Array(合并排序數組)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.