当前位置:网站首页>调整数组顺序使奇数位于偶数前面——每日两题
调整数组顺序使奇数位于偶数前面——每日两题
2022-07-28 05:32:00 【墨客小书虫】
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
又是每天早晨起来刷题的时候了,刷题真的太有意思了,每天两道题,一起加油哦️

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
提示:
0 <= nums.length <= 500000 <= nums[i] <= 10000
思路
算法:双指针。
首先因为有序数组,所以基本判断是双指针,判断是否奇数
nums[left]%2==1,左指针是奇数就右移动,如果右指针是偶数就左移动,如果两个指针,左边是偶数,右边是奇数,就互相交换,这道题结束了。
public class 调整数组顺序使奇数位于偶数前面 {
public int[] exchange(int[] nums) {
int left=0;
int right=nums.length-1;
int temp=0;
while (left<right){
if (nums[left]%2==1){
left++;
}else if (nums[right]%2==0){
right--;
}else {
temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
left++;
right--;
}
}
return nums;
}
}
边栏推荐
- Pytorch - storage and loading model
- shell---条件语句练习
- NAT network address translation
- Layer 3 switching and VRRP
- 隔离级别RR、间隙锁、幻读
- Shell--第一天作业
- easypoi一对多,合并单元格,并且根据内容自适应行高
- Standard C language learning summary 8
- Basic usage and precautions of arrow function (= >) and three-point operator (...) in ES6 (this points to)
- Shortest seek time first (SSTF)
猜你喜欢

freemarker合并单元格,if、else标签的使用,null、空字符串处理

JS secondary linkage Department

Easypoi export interlaced style settings

Remotely access the local website of services such as neo4j on the ECS

guava之guava cache

GFS distributed file system

Freemaker merges cells, uses if and else tags, and processes null and empty strings

Install Nessus under Kali

guava之Retryer

Leetcode then a deep copy of the linked list
随机推荐
Tailing microelectronics B91 general development board integrated into the trunk of openharmony community
高性能内存队列-Disruptor
Reptile learning summary
GFS分布式文件系统
Use of C3d
Generate create table creation SQL statement according to excel
Standard C language learning summary 9
大话持久性与redolog
CAS vs 数据库乐观锁
VLAN configuration
Anaconda3 cannot open navigator solution
Basic knowledge of video format: let you know MKV, MP4, h.265, bit rate, color depth, etc
一口气学完4种 Redis 集群方案,真是各有千秋
Standard C language learning summary 8
Shell--- function
小红花STL
PyTorch - Dropout: A Simple Way to Prevent Neural Networks from Overfitting
5G 商用第三年:无人驾驶的“上山”与“下海”
Log in to heroku and the solution of IP address mismatch appears
Redis主从复制原理及配置