Comments (3)
解题思路
- 新建空数组, 双指针从前往后依次遍历两数组, 将值按顺序填充.
代码
public static void func(int[] nums1, int m, int[] nums2, int n) {
// 新构造一个数组
int[] nums = new int[m + n];
int i = 0, j = 0, index = 0;
while (i < m || j < n) {
// 双指针遍历两数组, 每次选择小值放入新数组中
if (j >= n) {
while (i < m) nums[index++] = nums1[i++];
break;
}
if (i >= m) {
while (j < n) nums[index++] = nums2[j++];
break;
}
if (nums1[i] < nums2[j])
nums[index++] = nums1[i++];
else
nums[index++] = nums2[j++];
}
System.arraycopy(nums,0,nums1,0,nums.length);
}
from pisecespeng.record.me.
LeetCode题解
解题思路
- 将两数组合并, 再排序
代码
public static void func(int[] nums1, int m, int[] nums2, int n) {
for (int i = 0; i != n; ++i) {
nums1[m + i] = nums2[i];
}
Arrays.sort(nums1);
}
from pisecespeng.record.me.
LeetCode题解
解题思路
- 逆向双指针,
- 正向双指针之所以需要开辟新的数组, 就是因为元素覆盖的问题,
- 逆向双指针则不需要考虑这个问题.
代码
public static void func(int[] nums1, int m, int[] nums2, int n) {
int p1 = m - 1, p2 = n - 1;
int tail = m + n - 1;
int cur;
while (p1 >= 0 || p2 >= 0) {
if (p1 == -1) {
cur = nums2[p2--];
} else if (p2 == -1) {
cur = nums1[p1--];
} else if (nums1[p1] > nums2[p2]) {
cur = nums1[p1--];
} else {
cur = nums2[p2--];
}
nums1[tail--] = cur;
}
}
from pisecespeng.record.me.
Related Issues (20)
- 两数相加 HOT 2
- 买卖股票的最佳时机 HOT 3
- 买卖股票的最佳时期2 HOT 3
- 二叉树的层序遍历 HOT 2
- 二叉树的最大深度 HOT 2
- 二进制求和 HOT 4
- 从尾到头打印链表 HOT 2
- 位1的个数 HOT 4
- 删除排序数组中的重复项 HOT 2
- 删除链表的倒数第N个节点 HOT 3
- 加一 HOT 2
- 反转字符串 HOT 2
- 反转链表 HOT 3
- 只出现一次的数字 HOT 2
- 合并两个有序链表 HOT 2
- 回文数 HOT 2
- 回文链表 HOT 3
- 复制带随机指针的链表 HOT 2
- 外观数列 HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pisecespeng.record.me.