One. Problem Description
Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.
Description:
And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of 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]
two. Problem-solving ideas
Thinking this problem: a method using the double pointer array solved.
Step a: setting a first number of points in the array nums1, b nums2 point array of the first number.
Step two: Starting from the array nums1 traversal to find a b larger than the first number, the new location for a.
Step 3: At this time, the back of a digital mobile nums1 array inside a, b and a position of insertion.
Step Four: a ++, b ++, it determines whether the array b nums2 traversal is complete, otherwise returns to step two.
three. Results of the
When execution: 1 ms, beat the 76.21% of all users in java submission
Memory consumption: 36 MB, defeated 85.86% of all users in java submission
four. Java code
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int a=0; int b=0; if(n==0) return; while(b<nums2.length) { for(int i=a;i<nums1.length;i++) { if(nums1[i]>nums2[b]||i==m) { int j=m-1; while(i<=j) { nums1[j+1]=nums1[j]; j--; } nums1[i]=nums2[b]; m++; a=i+1; break; } } b++; } } }