[leetcode]88.Merge Sorted Array

來源:互聯網
上載者:User

標籤:sort   tco   put   tput   排序   hold   equal   元素   解法   

題目

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

解法一思路

最先想到的是把num2直接複製到nums1後面,然後進行個排序即可。時間複雜度取決於排序演算法。

代碼
class Solution {    public void merge(int[] nums1, int m, int[] nums2, int n) {        int j = 0;        for(int i = m; i < m+n; i++) {            nums1[i] = nums2[j++];        }        Arrays.sort(nums1);    }}
解法二思路

這種方法直接建立一個新的m+n的數組,然後比較num1和nums2的當前元素,將較小的值插入新數組,依次迴圈即可。但是這種方法違反了題目的本意,因為題目並不想讓建立新數組,所以此種方法不寫代碼了,瞭解即可。

解法三思路

這種方法比較精妙,由於合并後的數組必然是m+n的,所以我們可以從後往前開始賦值,先將nums1和nums2的較大值放到m+n-1的位置上,然後依次向前推。如果迴圈結束,當n不為0但m為0時,num1剩下的元素就在相應的位置,不用處理。當m不為0但n為0,那就把nums2剩下的數依次複製過去。

代碼
class Solution {    public void merge(int[] nums1, int m, int[] nums2, int n) {        int i = n+m-1;        int j = m-1;        int k = n-1;        while(j >= 0 && k >= 0)            nums1[i--] = nums1[j] > nums2[k]?nums1[j--]:nums2[k--];        while(k >= 0)            nums1[i--] = nums2[k--];    }}

[leetcode]88.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.