当前位置:网站首页>leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
2022-07-30 08:52:00 【kt1776133839】
题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。
样例:
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
提示:
0 <= nums.length <= 50000
0 <= nums[i] <= 10000
解题思路:
考虑定义双指针 iii , jjj 分列数组左右两端,循环执行:
指针 iii 从左向右寻找偶数;
指针 jjj 从右向左寻找奇数;
将 偶数 nums[i]nums[i]nums[i] 和 奇数 nums[j]nums[j]nums[j] 交换。
可始终保证: 指针 iii 左边都是奇数,指针 jjj 右边都是偶数 。

Java程序:
class Solution {
public int[] exchange(int[] nums) {
int i = 0, j = nums.length - 1, tmp;
while(i < j) {
while(i < j && (nums[i] & 1) == 1) i++;
while(i < j && (nums[j] & 1) == 0) j--;
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
边栏推荐
猜你喜欢

负电压电路(原理分析)

怎么在本地电脑上运行dist文件

初识Apifox——如何使用Apifox做一个简单的接口测试

Two solutions for Excel xlsx file not supported

编程界的“躲猫猫”比赛 | 每日趣闻

C语言经典练习题(3)——“汉诺塔(Hanoi)“

How to implement Golang DES encryption and decryption?

C#中Config文件中,密码的 特殊符号的书写方法。

Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】

【云原生】Kubernetes入门详细讲解
随机推荐
PyTorch安装及环境配置(Win10)
内卷下的智能投影行业,未来何去何从?
嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
日志导致线程Block的这些坑,你不得不防
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
Explain the problem of change exchange in simple terms - the shell of the backpack problem
一文读懂二十种开关电源拓扑结构
Circuit analysis: constant current source circuit composed of op amp and triode
七大排序之直接选择排序
[Yugong Series] July 2022 Go Teaching Course 021-Slicing Operation of Go Containers
leetcode 剑指 Offer 42. 连续子数组的最大和
PCB板加工流程中哪些因素会影响到传输线阻抗
CSDN21天学习挑战赛
延迟队列MQ
详解JVM垃圾回收
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
电源完整性基础知识
Taosi TDengine 2.6+ optimization parameters
团队级敏捷真的没你想的那么简单
Kotlin 值类 - value class