鱼C论坛

 找回密码
 立即注册
查看: 2560|回复: 0

[学习笔记] leetcode 88. Merge Sorted Array

[复制链接]
发表于 2019-9-2 06:02:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2019-9-2 07:01 编辑
  1. Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

  2. Note:

  3. The number of elements initialized in nums1 and nums2 are m and n respectively.
  4. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
  5. Example:

  6. Input:
  7. nums1 = [1,2,3,0,0,0], m = 3
  8. nums2 = [2,5,6],       n = 3

  9. Output: [1,2,2,3,5,6]
复制代码

  1. class Solution {
  2.     public void merge(int[] nums1, int m, int[] nums2, int n) {
  3.         
  4.         if(n == 0) return;
  5.         
  6.         if(m == 0){
  7.             
  8.             for(int i = 0; i< n; i++){
  9.                
  10.                 nums1[i] = nums2[i];
  11.             }
  12.         }
  13.                
  14.         int count1 = 0, count2= 0, count3= 0;
  15.         
  16.         int[] arr = new int[m+n];
  17.         
  18.         while(count1 != (m+n)){
  19.             
  20.             if(count3 < n && (count2 == m || nums1[count2] >= nums2[count3])){
  21.                
  22.                 arr[count1++] = nums2[count3++];
  23.             }
  24.             else if(count2 < m && (count3 == n || nums1[count2] < nums2[count3])){
  25.                
  26.                 arr[count1++] = nums1[count2++];
  27.             }
  28.         
  29.         }
  30.         
  31.         for(int i = 0; i< arr.length; i++){
  32.             
  33.             nums1[i] = arr[i];
  34.         }
  35.         
  36.     }
  37. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 18:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表