[leetcode]88. 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]

思路

1.  use pointer i to scan nums1, pointer j to scan nums2

2. find the larger item between such two given arrays

3. throw such item into the new merged array

代码

 1 class Solution {
 2     public void merge(int[] nums1, int m, int[] nums2, int n) {
 3         int k = m+n-1; //new merged array's length
 4         int i = m-1; 
 5         int j = n-1;
 6         
 7         while(j >= 0){
 8              // kinda merge sort algorithm, find the larger item
 9             if(i >= 0 && nums1[i] > nums2[j]){
10                 // throw such item into the new merged array
11                 nums1[k] = nums1[i];
12                 i--;
13             }else{
14                 // throw larger item into the new merged array
15                 nums1[k] = nums2[j];
16                 j--;
17             }
18             // make sure from right to left, new merged array is in decescending order
19             k--;
20         }
21     }
22 }
扫描二维码关注公众号,回复: 3639343 查看本文章

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9820383.html