【LeetCode】- Merge Sorted Array (合并有序數組)

來源:互聯網
上載者:User

標籤:style   blog   color   java   io   strong   ar   for   2014   

[ 問題: ]

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

直譯:給定兩個排好序的整形數組,將數組B合并到數組A,形成一個新的數組。


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 m and n respectively.


[ 解法: ]

題解:從結尾開始歸併,不會覆蓋元素又能滿足題意。
參數m:數組m位置後面元素會被數組B中元素替換
參數n:從第一個開始,將數組B中n個元素會被合并到數組A

public class Solution {public static void main(String[] args) {int[] A = { 1, 2, 4, 5, 6, 8 };int[] B = { 3, 9, 10 };new Solution().merge(A, 3, B, 2);  // 1 2 3 4 9 8}public void merge(int A[], int m, int B[], int n) {int i, j, k;for (i = m - 1, j = n - 1, k = m + n - 1; k >= 0; --k) {if (i >= 0 && (j < 0 || A[i] > B[j])) {A[k] = A[i--];} else {A[k] = B[j--];}}}}



【LeetCode】- 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.