Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

合并两个有序数组 #365

Open
lzxjack opened this issue Jan 11, 2023 · 1 comment
Open

合并两个有序数组 #365

lzxjack opened this issue Jan 11, 2023 · 1 comment

Comments

@lzxjack
Copy link
Contributor

lzxjack commented Jan 11, 2023

No description provided.

@xiaodye
Copy link

xiaodye commented Jan 12, 2023

双指针法

/**
 * 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
 * @param nums1
 * @param m
 * @param nums2
 * @param n
 */
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
  // 初始化两个指针的指向,初始化 nums1 尾部索引k
  let i = m - 1;
  let j = n - 1;
  let k = m + n - 1;

  while (i >= 0 && j >= 0) {
    // 取较大的值,从末尾往前填补
    if (nums1[i] >= nums2[j]) {
      nums1[k] = nums1[i];
      i--;
      k--;
    } else {
      nums1[k] = nums2[j];
      j--;
      k--;
    }
  }

  // nums2 留下的情况,特殊处理一下
  while (j >= 0) {
    nums1[k] = nums2[j];
    j--;
    k--;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants