当前位置:网站首页>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;
}
}
边栏推荐
- 团队级敏捷真的没你想的那么简单
- 浅论各种调试接口(JTAG、SWD、RDI、Jlink、Ulink、STlink)的区别
- 342 · Valley Sequence
- Unity performance analysis Unity Profile performance analysis tool
- 一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
- C语言经典练习题(3)——“汉诺塔(Hanoi)“
- 仿牛客网项目第一章:开发社区首页(详细步骤和思路)
- PyQt5快速开发与实战 7.4 事件处理机制入门 and 7.5 窗口数据传递
- Google Cloud Spanner的实践经验
- It is said that FPGA is high-end, what can it do?
猜你喜欢

Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"

硬件工程师

69. Sqrt(x)x 的平方根

Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上

负电压电路(原理分析)

百度paddleocr检测训练

统一异常处理导致ResponseBodyAdvice失效

Access to display the data

企业数字化建设,自研还是采购?

Explain the problem of change exchange in simple terms - the shell of the backpack problem
随机推荐
Jetpack Compose 从入门到入门(八)
How to run dist file on local computer
Circuit analysis: constant current source circuit composed of op amp and triode
CSDN21天学习挑战赛
积分专题笔记-与路径无关条件
MySQL【运算符】
获取显示器数据
[Fun BLDC series with zero basics] Taking GD32F30x as an example, the timer related functions are explained in detail
电源完整性的去耦和层间耦合电容
【零基础玩转BLDC系列】以GD32F30x为例定时器相关功能详解
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
HCIP --- MPLS VPN实验
负电压电路(原理分析)
日志导致线程Block的这些坑,你不得不防
企业数字化建设,自研还是采购?
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
Test automation selenium (a)
深入浅出零钱兑换问题——背包问题的套壳
七大排序之直接选择排序
TreeSet解析