如何重新排列数组使得数组左边为奇数,右边为偶数,并使得空间复杂度为O(1),时间复杂度为O(n)
2024-10-19 22:27:26
思路分析:
类似快速排序的处理。可以用两个指针分别指向数组的头和尾,头指针正向遍历数组,找到第一个偶数,尾指针逆向遍历数组,找到第一个奇数,使用引用参数传值交换两个指针指向的数字,然后两指针沿着相应的方向继续向前移动,重复上述步骤,直到头指针大于等于尾指针为止。
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
void Swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void ReverseArray(int arr[], int len)
{
if (arr == NULL || len <= 0)
printf("数组中无元素,变换毛线啊。");
else
{
int begin = 0;
int end = len - 1;
while (begin < end)
{
while (arr[begin] % 2 == 1 && end>begin)
begin++;
while (arr[end] % 2 == 0 && end > begin)
end--;
Swap(arr[begin], arr[end]);
}
}
}
int main()
{
int array[] = { 1, 23, 2, 34, 21, 45, 26, 22, 41, 66, 74, 91, 17, 64 };
int len = sizeof(array) / sizeof(array[0]);
int i;
printf("原数组为:");
for (i = 0; i < len; i++)
printf("%d ", array[i]);
printf("\n");
ReverseArray(array, len);
printf("经过变换后的数组为:");
for (i = 0; i < len; i++)
printf("%d ", array[i]);
printf("\n");
getchar();
return 0;
}
效果如图:
最新文章
- 我们为什么要使用maven,公司推行maven杂谈
- 国内第一部C#.Net调用Matlab混合编程视频教程
- Raspberry Pi 学习笔记之一
- Hadoop及其相关组件简介
- mysql学习(二)
- Android 设置VPN(pptp连接方式)
- sessionStorage和localStorage中 存储
- 剑指Offer06 旋转数组的最小值
- TCP三次握手和连接关闭过程详解
- JS操作URL
- 万马齐喑究可哀-中文编程的又一波";讨论";
- [nodejs] nodejs开发个人博客(五)分配数据
- 2018 UESTC 线段树专题
- Mac系统下 PHP7安装Swoole扩展 教程
- Python实现批量梯度下降算法
- hihocoder博弈游戏&#183;Nim游戏&#183;三
- 阅读笔记:Solving the “false positives” problem in fraud prediction
- MVC模式:python案例
- hud 5124 lines(思维 + 离散化)
- mysql中用户和权限
热门文章
- 让QtCreator在调试时显示字符串 Qt调试助手 QtDebuggingHelper qtc-debugging-helper
- strcpy_s与strcpy的区别
- tomcat部署时war和war exploded区别
- 【转】【Python】 python中的编码问题报错 &#39;ascii&#39; codec can&#39;t decode 及 URL地址获取中文
- SpagoBI 教程 Lesson 1:Introduction and Installation
- Linux中的绝对路径和相对路径
- e864. 取的显示器大小尺寸
- WCF Service 配置文件注释(转)
- CSS :after、before、<;!DOCTYPE>;
- 【转】Spring Boot干货系列:常用属性汇总