摘要:題目要求將兩個(gè)有序數(shù)組合并至其中一個(gè)數(shù)組并且該新數(shù)組仍然有序。所以我們可以換一種思維方式,從大至小遍歷,這樣可以將較大的元素直接填入當(dāng)前的位置而且不用考慮移動(dòng)其它的元素。
題目要求
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.
將兩個(gè)有序數(shù)組合并至其中一個(gè)數(shù)組并且該新數(shù)組仍然有序。
思路和代碼一般的合并數(shù)組,我們會考慮利用一個(gè)新數(shù)組,并用兩個(gè)指針分別遍歷并順序比較兩個(gè)數(shù)組的元素,將較小的那個(gè)那個(gè)元素添加至結(jié)果數(shù)組之中。
但是此時(shí)我們需要將兩個(gè)數(shù)組合并至已存在的一個(gè)數(shù)組之中,如果還是按照那種方法,我們需要在插入元素之后將當(dāng)前的元素順序后移,這回帶來巨大的性能損耗。所以我們可以換一種思維方式,從大至小遍歷,這樣可以將較大的元素直接填入當(dāng)前的位置而且不用考慮移動(dòng)其它的元素。這種方法的時(shí)間復(fù)雜度為O(m+n)
代碼如下:
public void merge(int[] nums1, int m, int[] nums2, int n) { //nums1的指針 int pointer1 = m-1 ; //nums2的指針 int pointer2 = n-1 ; for(int j = m+n-1 ; pointer1>=0 && pointer2>=0 && j>pointer1 ; j--){ if(nums2[pointer2] >= nums1[pointer1]){ nums1[j] = nums2[pointer2--]; }else{ nums1[j] = nums1[pointer1--]; } } //將剩余的nums2中的元素填入nums[1] while(pointer2>=0){ nums1[pointer2] = nums2[pointer2]; pointer2--; } }
總之,挺簡單的一道題
想要了解更多開發(fā)技術(shù),面試教程以及互聯(lián)網(wǎng)公司內(nèi)推,歡迎關(guān)注我的微信公眾號!將會不定期的發(fā)放福利哦~
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/67119.html
摘要:題目假設(shè)數(shù)組的長度大于需要排序的元素?cái)?shù)量數(shù)組的后位為。解法看到這道題時(shí)一種常規(guī)思路可能是,從頭遍歷兩個(gè)數(shù)組,將的元素插入到的合適的位置。 題目詳情 Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 題目的意思是,輸入兩個(gè)已經(jīng)排好序的數(shù)組nums1和nu...
摘要:自己沒事刷的一些的題目,若有更好的解法,希望能夠一起探討項(xiàng)目地址 自己沒事刷的一些LeetCode的題目,若有更好的解法,希望能夠一起探討 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。 順序整理 1~50 1...
Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...
摘要:但是如果我們從后往前,合并到第一個(gè)數(shù)組的最后,則不用位移。注意將和都先減,用和來代表下標(biāo),避免兩個(gè)數(shù)組為空時(shí)拋出空指針異常。 Merge Sorted Array 最新更新請見:https://yanjia.me/zh/2019/02/... Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1...
閱讀 1468·2021-09-26 09:55
閱讀 1981·2019-08-30 12:45
閱讀 1142·2019-08-29 11:20
閱讀 3614·2019-08-26 11:33
閱讀 3503·2019-08-26 10:55
閱讀 1749·2019-08-23 17:54
閱讀 2469·2019-08-23 15:55
閱讀 2403·2019-08-23 14:23