当前位置:网站首页>【剑指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;
}
};
边栏推荐
- With a lamp inserted in the nostril, the IQ has risen and become popular in Silicon Valley. 30000 yuan is enough
- CLP information - No. 1 central document on Strengthening Rural Revitalization financial services
- postgresql创建数据库
- Laravel 8 uses passport for auth authentication and token issuance
- 面试经典题目:怎么做的性能测试?【杭州多测师】【杭州多测师_王sir】
- How to predict SQL statement query time?
- 项目经理如何击退被工作汇报支配的恐惧感?
- 书籍《阅读的方法》读后感
- Hands on, how should selenium deal with pseudo elements?
- Easy to use GS_ Dump and GS_ Dumpall command export data
猜你喜欢

什么是泛型?为什么要使用泛型?泛型怎么用?那包装类呢?

What happened to the frequent disconnection of the computer at home

jdbc调试错误,求指导

How to predict SQL statement query time?

大龄码农从北京到荷兰的躺平生活

Will you be punished for not wearing seat belts in the back row?

Analysis of breadcrumb usage scenarios on websites

C# 启动一个外部exe文件,并传入参数

整了20张高清数据分析全知识地图,强烈建议收藏!

PyQt5 使QPlainTextEdit控件支持行号显示
随机推荐
Opengauss database flashback function verification
Easy to use GS_ Dump and GS_ Dumpall command export data
[Yugong series] June 2022 Net architecture class 078 worker cluster of distributed middleware schedulemaster
Using cloud DB to build apps quick start - quick games
Application of AI in index recommendation
GO语言-数组Array
How to optimize the performance of compose? Find the answer through "underlying principles" | developers say · dtalk
postgresql创建数据库
09 Minimum Spanning Tree highway
Tianjin Port coke wharf hand in hand map flapping software to visually unlock the smart coke port
How does the taskbar under the computer display open programs
Analysis of breadcrumb usage scenarios on websites
Implementation of VGA protocol based on FPGA
Hands on, how should selenium deal with pseudo elements?
搜索与图论:Dijkstra求最短路 I—Dijkstra(最短路径)
书籍《阅读的方法》读后感
Memory optimization table mot management
真香,华为主动离职也给 N+1
AutoRunner自动化测试工具如何创建项目-Alltesting|泽众云测试
Using cloud DB to build app quick start - quick application