[leetcode]88. Merge Sorted Array归并有序数组
2024-10-12 10:18:59
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
代码
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int k = m+n-1; //new merged array's length
int i = m-1;
int j = n-1; while(j >= 0){
// kinda merge sort algorithm, find the larger item
if(i >= 0 && nums1[i] > nums2[j]){
// throw such item into the new merged array
nums1[k] = nums1[i];
i--;
}else{
// throw larger item into the new merged array
nums1[k] = nums2[j];
j--;
}
// make sure from right to left, new merged array is in decescending order
k--;
}
}
}
最新文章
- java——HashMap的实现原理,自己实现简单的HashMap
- gulp操作基本功能.md
- 【iCore3 双核心板】例程二十:LAN_TCPC实验——以太网数据传输
- (转)现代C++函数式编程
- Codeforces Round #337 (Div. 2) C. Harmony Analysis 数学
- shell 1变量注意点
- [LeetCode235]Lowest Common Ancestor of a Binary Search Tree
- 物料事务处理接口表 MTL_TRANSACTIONS_INTERFACE 账户别名使用 及 提示无效的分配账户字段
- nginx集成环境下载
- HTML语法介绍
- 本地文件上传GitHub
- 安装ORACLE高可用RAC集群11g校验集群安装的可行性输出信息
- Create rolling monthly, weekly and daily Logstash indices
- Esper学习之十五:Pattern(二)
- oclif cli app开发简单试用
- VUE router-view 页面布局 (嵌套路由+命名视图)
- 《敏捷软件开发-原则、方法与实践》-Robert C. Martin读书笔记(转)
- .Net遍历窗体上控件
- TEXTBOX属性TEXTMODE设置为PASSWORD后,后台不能给这个TEXTBOX赋值原因
- MyBatis与JDBC的对比