leetcode88 合并两个有序数组
leetcode88 合并两个有序数组
//20220319
写在前面:昨天开始恢复刷题,今天刷到这个,妈耶竟然写了我一个小时,都是因为注意力不集中,简直在浪费时间/无语,在此记录一下解法
题目描述
- 题目链接:点我
- 题目描述:
给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
解法思路&代码:
- 解法思路:双指针,然后以nums1为主遍历序列,如果nums1指针对应数据大于nums2指针对应值,则进行数据移动
- 代码如下:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(n==0) return;
if(m==0) {
System.arraycopy(nums2, 0, nums1, 0, nums1.length);
return;
}
int first;
int second;
int index = 0;
for(int j = m;j<nums1.length;++j){
nums1[j] = Integer.MAX_VALUE;
}
for(int i = 0;i<nums1.length&&index<n;++i){
first = nums1[i];
second = nums2[index];
if(first>second){
if (m + index - i >= 0) System.arraycopy(nums1, i, nums1, i + 1, m + index - i);
nums1[i] = nums2[index];
index++;
}
}
}
}
- 通过截图
以上
希望对后来者有所帮助
/抱拳