最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實(shí)現(xiàn)LeetCode(88.混合插入有序數(shù)組)

 更新時(shí)間:2021年07月13日 14:24:46   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(88.混合插入有序數(shù)組),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 88. Merge Sorted Array 混合插入有序數(shù)組

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

Note:

  • The number of elements initialized in nums1and 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]

混合插入有序數(shù)組,由于兩個(gè)數(shù)組都是有序的,所有只要按順序比較大小即可。題目中說(shuō)了 nums1 數(shù)組有足夠大的空間,說(shuō)明不用 resize 數(shù)組,又給了m和n,那就知道了混合之后的數(shù)組的大小,這樣就從 nums1 和 nums2 數(shù)組的末尾開始一個(gè)一個(gè)比較,把較大的數(shù),按順序從后往前加入混合之后的數(shù)組末尾。需要三個(gè)變量 i,j,k,分別指向 nums1,nums2,和混合數(shù)組的末尾。進(jìn)行 while 循環(huán),如果i和j都大于0,再看如果 nums1[i] > nums2[j],說(shuō)明要先把 nums1[i] 加入混合數(shù)組的末尾,加入后k和i都要自減1;反之就把 nums2[j] 加入混合數(shù)組的末尾,加入后k和j都要自減1。循環(huán)結(jié)束后,有可能i或者j還大于等于0,若j大于0,那么還需要繼續(xù)循環(huán),將 nums2 中的數(shù)字繼續(xù)拷入 nums1。若是i大于等于0,那么就不用管,因?yàn)榛旌蠑?shù)組本身就放在 nums1 中,參見代碼如下:

解法一: 

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

我們還可以寫的更簡(jiǎn)潔一些,將兩個(gè) while 循環(huán)融合到一起,只要加上 i>=0 且 nums1[i] > nums2[j] 的判斷條件,就可以從 nums1 中取數(shù),否則就一直從 nums2 中取數(shù),參見代碼如下:

解法二:

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

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(88.混合插入有序數(shù)組)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)混合插入有序數(shù)組內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

万山特区| 莱芜市| 日土县| 昌平区| 铜陵市| 睢宁县| 拜泉县| 七台河市| 长治县| 手游| 岳阳市| 井冈山市| 柳河县| 吉木乃县| 农安县| 固镇县| 陆丰市| 夏河县| 台中市| 句容市| 萍乡市| 玉林市| 泽普县| 沧州市| 灵丘县| 江油市| 杭锦旗| 湟中县| 兴业县| 五大连池市| 星子县| 太原市| 乳山市| 孙吴县| 安图县| 东乡县| 玉田县| 新宁县| 永靖县| 长治市| 祁东县|