当前位置:网站首页>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;
}
}
边栏推荐
- C语言经典练习题(3)——“汉诺塔(Hanoi)“
- Network/Information Security Top Journal and Related Journals Conference
- 读书笔记:《这才是心理学:看穿伪心理学的本质(第10版)》
- Only after such a stage of development can digital retail have a new evolution
- EMC过不了?都是PCB工程师的锅?
- 详解JVM垃圾回收
- MySQL中使用IN 不会走索引分析以及解决办法
- How to use Jmeter to carry out high concurrency in scenarios such as panic buying and seckill?
- 获取显示器数据
- How to implement Golang DES encryption and decryption?
猜你喜欢
随机推荐
Network/Information Security Top Journal and Related Journals Conference
MySQL【运算符】
leetcode 剑指 Offer 48. 最长不含重复字符的子字符串
HCIP --- MPLS VPN实验
leetcode 剑指 Offer 42. 连续子数组的最大和
Kotlin value class - value class
Version management of public Jar packages
硬件工程师
激活数据潜力 亚马逊云科技重塑云上存储“全家桶”
函数式接口&Lambda表达式——简单应用笔记
Unreal Engine Graphic Notes: could not be compiled. Try rebuilding from source manually. Problem solving
Only after such a stage of development can digital retail have a new evolution
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
HashSet和LinkedHashSet
Test automation selenium (a)
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
九九乘法表
20220728使用电脑上的蓝牙和汇承科技的蓝牙模块HC-05配对蓝牙串口传输
PCB板加工流程中哪些因素会影响到传输线阻抗
详解JVM垃圾回收









