生活随笔
收集整理的這篇文章主要介紹了
双指针:88. 合并两个有序数组
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接
88. 合并兩個有序數(shù)組
解題思路
一. 合并數(shù)組后排序,時間復(fù)雜度為O((n+m)log(n+m))
代碼:
快排詳解
class Solution {public void merge(int[] nums1
, int m
, int[] nums2
, int n
) {for(int i
=m
,j
=0;i
<m
+n
;i
++,j
++){nums1
[i
] = nums2
[j
];}quickSort(nums1
,0, m
+n
-1);}public void quickSort(int nums
[], int low
, int high
){if(low
<high
){int basicIndex
= qSort(nums
, low
, high
);quickSort(nums
, low
, basicIndex
-1);quickSort(nums
, basicIndex
+1, high
);}}public int qSort(int nums
[], int low
, int high
){int basic
= nums
[low
];while(low
<high
){while(low
<high
&&nums
[high
]>basic
)high
--;nums
[low
] = nums
[high
];while(low
<high
&&nums
[low
]<=basic
)low
++;nums
[high
] = nums
[low
];}nums
[low
] = basic
;return low
;}}
二、利用兩個數(shù)組已經(jīng)排序的特點(diǎn),使用三指針,時間復(fù)雜度O(log(n+m)),執(zhí)行步驟如下:
p1指向nums1的最大值(p1=m-1),p2指向nums2的最大值(p2=n-1),current指向當(dāng)前排序的位置(從后往前排,即從大到小,current=m+n-1)從后往前排序:nums1[current] = max(nums1[p1], nums2[p2]),具體看代碼注釋
動畫演示(圖作者:https://leetcode-cn.com/problems/merge-sorted-array/solution/88-by-ikaruga/):
代碼:
class Solution {public void merge(int[] nums1
, int m
, int[] nums2
, int n
) { int p1
= m
-1,p2
= n
-1,current
=m
+n
-1;while(current
>=0&&p2
>=0){if(p1
>=0&&nums1
[p1
]>nums2
[p2
]){nums1
[current
] = nums1
[p1
];p1
--;}else{nums1
[current
] = nums2
[p2
];p2
--;}current
--;}}}
總結(jié)
以上是生活随笔為你收集整理的双指针:88. 合并两个有序数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。