9

Leetcode 88 合并两个有序数组

 3 years ago
source link: https://segmentfault.com/a/1190000040401198
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Leetcode 88 合并两个有序数组

发布于 今天 15:13

给你两个有序整数数组 nums1nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。

初始化 nums1nums2 的元素数量分别为 mn 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nums2 的元素。

输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]

输入:nums1 = [0], m = 0, nums2 = [1], n = 1
输出:[1]

输入:nums1 = [5, 6, 7, 8, 0, 0, 0], m = 4, nums2 = [2, 3, 3], n = 3
输出:[2, 3, 3, 5, 6, 7, 8]

public class Solution {
  public void merge() {
    int a = m - 1; // nums1 的指针
    int b = n - 1; // nums2 的指针
    int p = m + n - 1; // 插入元素的指针
    while (a >= 0 && b >= 0) {
      if (nums1[a] > nums2[b]) {
        nums1[p] = nums1[a];
        a--;
      } else {
        nums1[p] = nums2[b];
        b--;
      }
      p--;
    }
    // 解决一开始 a = -1 和到最后 a = -1 但 b 还没遍历完的情况
    while (b >= 0) {
      nums1[p] = nums2[b];
      b--;
      p--;
    }
  }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK