题目链接
88. 合并两个有序数组
解题思路
一. 合并数组后排序,时间复杂度为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;}}
二、利用两个数组已经排序的特点,使用三指针,时间复杂度O(log(n+m))
,执行步骤如下:
- p1指向nums1的最大值(p1=m-1),p2指向nums2的最大值(p2=n-1),current指向当前排序的位置(从后往前排,即从大到小,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) { // p1指向nums1的最大值,//p2指向nums2的最大值//current指向当前排序的位置int p1 = m-1,p2 = n-1,current=m+n-1;while(current>=0&&p2>=0){//p1>=0避免nums1为空数组,即m=0的情况//从p1,p2中挑出较大的值,并移动指针if(p1>=0&&nums1[p1]>nums2[p2]){nums1[current] = nums1[p1];p1--;}else{nums1[current] = nums2[p2];p2--;}current--;}}}