当前位置:网站首页>LeetCode 88:合并两个有序数组
LeetCode 88:合并两个有序数组
2022-06-28 04:14:00 【斯沃福德】
题目:
注意数组默认已经是升序。
方法一:
使用双指针p1 p2遍历两个数组;
过程和合并两个排序的链表类似
当p1 p2还未遍历到头,则从前向后判断p1 p2指针所指的元素,小的就放入r 数组;
当有任一数组到头了,则跳出循环,将未到头的那个数组继续添加至r 数组即可;
最后拷贝至nums1。
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] r=new int[nums1.length];
int p1=0;
int p2=0;
int curr=0;
while(p1<m && p2<n){
if(nums1[p1]<nums2[p2]){
r[curr++]=nums1[p1++];
}else{
r[curr++]=nums2[p2++];
}
}
//任一数组到头了
while(p1<m){
r[curr++]=nums1[p1++];
}
while(p2<n){
r[curr++]=nums2[p2++];
}
System.arraycopy(r,0,nums1,0,n+m);
}
}
方法二:Arrays.sort
先将nums2直接添加进nums1,然后使用Java自带API进行排序
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i=0;i<n;i++){
nums1[m+i]=nums2[i];
}
Arrays.sort(nums1);
}
}
边栏推荐
- [applet] solution document using font awesome Font Icon (picture and text)
- Sum of squares of each bit of a number
- Matlab exercises -- basic data processing
- inherit
- JS逆向之巨量星图sign签名
- Has anyone ever used CDC to synchronize to MySQL with a deadlock?
- 【Matlab红绿灯识别】红绿灯识别【含GUI源码 1908期】
- Why is the frame rate calculated by opencv wrong?
- 多线程实现 重写run(),怎么注入使用mapper文件操作数据库
- flinkcdc采集oracle,oracle数据库是CDB的
猜你喜欢

Ppt production tips

Google Earth engine (GEE) - global flood database V1 (2000-2018)

CUPTI error: CUPTI could not be loaded or symbol could not be found.

Digital promising, easy to reach, Huawei accelerates the layout of the commercial market with "five pole" star products

抖音實戰~關注博主

The company leader said that if the personal code exceeds 10 bugs, he will be dismissed. What is the experience?

Design a stack with getmin function

Project practice! Teach you JMeter performance test hand in hand

云厂商为什么都在冲这个KPI?

Meta universe standard forum established
随机推荐
Principle of event delegation
Annual comprehensive analysis of China's audio market in 2022
Multithreading and high concurrency V: detailed explanation of wait queue, executor and thread pool (key)
The growth summer challenge is coming | learn and create two major tracks, and start the tutor registration!
A bit of knowledge - online resources on Chinese Learning
Sword finger offer 49 Ugly number (three finger needling technique)
知识点滴 - 关于汉语学习的网络资源
[matlab traffic light identification] traffic light identification [including GUI source code 1908]
Has any boss ever seen repeated binlog messages when MySQL CDC uses datastream
native关键字的作用
Has anyone ever used CDC to synchronize to MySQL with a deadlock?
How do I get the STW (pause) time of a GC (garbage collector)?
Audio and video technology development weekly
Mise en place d'un cadre d'essai d'automatisation de l'interface utilisateur - - rédaction d'une application d'automatisation
Project practice! Teach you JMeter performance test hand in hand
UI automation test framework construction - write an app automation
Role of native keyword
A queue of two stacks
Google Earth Engine(GEE)——全球洪水数据库 v1 (2000-2018年)
flinkcdc采集oracle,oracle数据库是CDB的