分析
难度 易
来源
https://leetcode.com/problems/merge-sorted-array/
题目
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]
解答
Runtime: 3 ms, faster than 99.99% of Java online submissions for Merge Sorted Array.
1 package LeetCode; 2 3 public class L88_MergeSortedArray { 4 public void merge(int[] nums1, int m, int[] nums2, int n) { 5 int len=m+n; 6 int count=0;//从后往前按顺序插入,已确定位置数字数目 7 int i=0,j=0;//i j分别为数组nums1 nums2上的游标 8 while(i<m&&j<n){ 9 if(nums1[m-1-i]>=nums2[n-1-j]){ 10 nums1[len-1-count]=nums1[m-1-i]; 11 i++; 12 count++; 13 } 14 else{ 15 nums1[len-1-count]=nums2[n-1-j]; 16 j++; 17 count++; 18 } 19 } 20 if(i<m){ 21 for(;i<m;i++){ 22 nums1[len-1-count]=nums1[m-1-i]; 23 count++; 24 } 25 }else if(j<n){ 26 for(;j<n;j++){ 27 nums1[len-1-count]=nums2[n-1-j]; 28 count++; 29 } 30 } 31 } 32 public static void main(String[] args){ 33 int[] nums1=new int[6];//[1,2,3,0,0,0] 34 int[] nums2=new int[3];//[2,5,6] 35 nums1[0]=1; 36 nums1[1]=2; 37 nums1[2]=3; 38 //nums2[0]=2; 39 nums2[0]=4; 40 nums2[1]=5; 41 nums2[2]=6; 42 L88_MergeSortedArray l88=new L88_MergeSortedArray(); 43 l88.merge(nums1,3,nums2,3); 44 for(int i=0;i<nums1.length;i++){ 45 System.out.print(nums1[i]+" "); 46 } 47 } 48 }