zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    大道至简第二篇阅读笔记
    大道至简第一篇阅读笔记
    冲刺第十天
    冲刺第九天
    冲刺第八天
    冲刺第七天
    用java构造一个带层次的文件目录遍历器
    用java进行简单的万年历编写
    delphi 图像处理 图像左旋右旋
    delphi 图像处理 图像放大缩小
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9820383.html
Copyright © 2011-2022 走看看