当前位置:网站首页>The sword refers to Offer | Adjust the order of the array so that the odd numbers come before the even numbers
The sword refers to Offer | Adjust the order of the array so that the odd numbers come before the even numbers
2022-08-07 14:03:00 【Lesser new】
输入一个长度为 n 整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前面部分, 所有的偶数位于数组的后面部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变.
方法1:
- 第一遍遍历,将奇数、Even numbers are put into two arrays respectively.(cntOdd number recorded,cnt2Even numbers are recorded)
- Put the even numbers into the odd number array as a result.
public int[] reOrderArray1(int[] array) {
int len = array.length;
int[] array1 = new int[len];
int[] array2 = new int[len];
int cnt = 0;
int cnt2 = 0;
for (int j : array) {
if ((j & 1) != 0) {
array1[cnt++] = j;
} else {
array2[cnt2++] = j;
}
}
System.arraycopy(array2,0,array1,cnt,cnt2);
return array1 ;
}
方法2:
- The first pass traverses the number of odd records
- Then take a double pointer,One loop will be odd、Even numbers are put into the result array.
public int[] reOrderArray(int[] array) {
int[] res=new int[array.length];
int cnt = 0;
for (int j : array) {
if ((j & 1) != 0) {
cnt++;
}
}
int x=0,y=cnt;
for(int j : array){
if((j&1)!=0){
res[x++] = j;
} else {
res[y++]=j;
}
}
return res;
}
努力、奋斗!
边栏推荐
- LeetCode_6142_统计坏数对的数目
- 下一代无线局域网-高吞吐率
- VMware's record of virtual machine expansion
- 【ASM】字节码操作 MethodVisitor 案例实战 cinit 方法生成
- Solidigm正式推出PCIe 4.0 固态盘Solidigm P41 Plus
- 使用cephadm部署单节点ceph集群,后期可扩容(基于官方文档,靠谱,读起来舒服)
- Realize database addition, deletion, modification and query in one page
- HJ3 明明的随机数
- 开发者成长激励计划-开发笔记:最简步骤移植LVGL
- mysql master-slave replication deployment
猜你喜欢

USB Module Analysis (4) - Device List & Permission Application

内存管理(五)——内存回收

实战 || 某软件股份有限公司通用漏洞挖掘

X64汇编语言指令编码

SQL教程之 掌握 SQL GROUP BY 的 5 个实用 SQL 示例(含完整sql与测试数据)

mysql database source command to import sql file records

mysql 主从复制部署

ENScanGo main domain name batch extraction script

内存管理(三)——内存分页

若依使用EasyExcel导入和导出数据
随机推荐
rpc.rquotad: unable to register (RQUOTAPROG, RQUOTAVERS, udp)
一种自主学习 Office Open XML 文件格式的方法介绍
2022/8/6
一个程序从编译到运行的全过程
NestedTensor
5 Practical SQL Examples for Mastering SQL GROUP BY in SQL Tutorial (including complete SQL and test data)
@RequestMapping注解标识的位置
07.自定义指令传参小窍门
图文详解:如何给女朋友解释什么是微服务?
HJ4 字符串分隔
C语言标准输入输出(11)
CSO面对面|对话迷你世界,畅谈游戏行业的安全建设
使用OpenCV测量图像中物体的大小
炒股用同花顺安全吗?资金会不会被转走?
Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
怎么简单实现菜单拖拽排序的功能
tensorRT(一)| tensorRT如何进行推理加速?
eyb: Creation process: build the environment to display the menu (1)
实现Sprite的Circle Fill效果及打了图集出现的问题
2022/8/5 拓扑排序+dp