当前位置:网站首页>【剑指Offer】21.调整数组顺序使奇数位于偶数前面
【剑指Offer】21.调整数组顺序使奇数位于偶数前面
2022-06-11 16:00:00 【LuZhouShiLi】
面试题21-调整数组顺序使奇数位于偶数前面
一、题目

二、思路
初始化:I,J双指针,分别指向数组nums左右两端
循环交换:当i >= j 跳出循环
- 指针i遇到奇数时则执行i = i + 1跳过,直到找到偶数
- 指针J遇到偶数则执行j = j - 1跳过,直到找到奇数
- 交换Nums[i]和nums[j]值
返回值:返回已经修改的nums数组
三、代码
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0,j = nums.size() - 1;
while(i < j)
{
while(i < j && (nums[i] & 1) == 1) i++;// 说明遇到了奇数 直接++ 与运算效率更高
while(i < j && (nums[j] & 1) == 0) j--; // 说明遇到了偶数 直接--
swap(nums[i],nums[j]);
}
return nums;
}
};
边栏推荐
- Understand the dense support functions / stored procedures of opengauss
- High concurrency pseudo sharing and cache line filling (cache line alignment) (@contained)
- postgresql启动过程
- 面试经典题目:怎么做的性能测试?【杭州多测师】【杭州多测师_王sir】
- dapr 思维导图
- Maui introductory tutorial series (1. framework introduction)
- Detailed explanation of MySQL binlog log and master-slave replication
- Talk about data center network again
- What happened to the frequent disconnection of the computer at home
- Overview and operation of database dense equivalent query
猜你喜欢

Go language slice

Learn automatic testing of postman interface from 0 to 1

It's really not human to let the express delivery arrive before the refund

无心剑英汉双语诗001. 《春游》

PyQt5 使QPlainTextEdit控件支持行号显示

Step 4 of installation in RF: an error is reported when installing the robotframework-selenium 2library

面试经典题目:怎么做的性能测试?【杭州多测师】【杭州多测师_王sir】

MAUI 入门教程系列(1.框架简介)

DHCP protocol instantiation analysis

From digital twinning to digital immortality, the "three-stage theory" of the development of the meta universe
随机推荐
This "invisible" robot may be your future colleague
How to manage concurrent write operations? Get you started quickly
How to predict SQL statement query time?
[从零开始学习FPGA编程-18]:快速入门篇 - 操作步骤2-6- VerilogHDL时序电路语法分析(以计数器为例)
[LeetCode每日一题] |686.重复叠加字符串匹配
From repeatedly rejected manuscripts to post-90s assistant professor, Wang Hao of Rutgers University: curiosity drives me to constantly explore
Dapr mind map
How the autorunner automated test tool creates a project -alltesting | Zezhong cloud test
GO语言-数组Array
Basic SQL statement - delete / update
jdbc调试错误,求指导
整了20张高清数据分析全知识地图,强烈建议收藏!
Overview and example analysis of opengauss database performance tuning
laravel 监听模式
How does the taskbar under the computer display open programs
Using cloud DB to build apps quick start - quick games
postgresql创建数据库
Yiwenjiaohui your database system tuning
完整的测试流程【杭州多测师】【杭州多测师_王sir】
3000 words to teach you how to use mot