【面试题】剑指offer14
来源:互联网 发布:乐视视频 mac 编辑:程序博客网 时间:2024/05/17 21:40
题目:
调整数组数据使奇数全部在偶数前面
解法一:
void oddnumberfront1(int *arr,int length){ if (arr==NULL||length==0) { return; } int* first; int* last; first=arr; last=arr+length-1; while(first<last) { while(first<last&&(*first& 0x1)!=0) { first++; } while (first<last&&(*last& 0x1)==0) { last--; } if(first<last) { int tmp=*first; *first=*last; *last=tmp; } }}
这种解法比较单一,只能解答这一种问题
解法二:将判断是否为偶数单独作为一个函数,这样要是限制条件改变后,只改变这个函数即可,下面添加了可被3整除的在后面,不被的在前面
#include<iostream>#include<cstdlib>using namespace std;bool isEven(int n)//判断是否为偶数{ return (n&1)==0;}bool is3multiplc(int n)//判断是否可以被3整除{ return (n%3)==0;}void Reorder(int *arr,int length,bool(*func)(int)){ if(arr==NULL||length==0) return; int * first=arr; int * last=arr+length-1; while(first<last) { while (first<last&&!isEven(*first)) { first++; } while (first<last&&isEven(*last)) { last--; } if(first<last) { int tmp=*first; *first=*last; *last=tmp; } }}void mulitplc(int *arr,int length,bool(*func)(int)){ if(arr==NULL||length==0) return; int * first=arr; int * last=arr+length-1; while(first<last) { while (first<last&&!is3multiplc(*first)) { first++; } while (first<last&&is3multiplc(*last)) { last--; } if(first<last) { int tmp=*first; *first=*last; *last=tmp; } }}void ReorderOddEven(int * arr,int length){ Reorder(arr,length,isEven);}void muliptlc3front(int * arr,int length){ mulitplc(arr,length,isEven);}void printArr(int* arr,int length){ if(arr==NULL||length==0) return; for (int i=0;i<length;i++) { cout<<arr[i]<<" "; } cout<<endl;}void test1(){ int arr[]={1,2,3,4,5,6,7,8,9}; ReorderOddEven(arr,9); printArr(arr,9); }void test2(){ int arr1[]={1}; ReorderOddEven(arr1,1); printArr(arr1,1);}void test3(){ int* arr2=NULL; ReorderOddEven(arr2,0); printArr(arr2,0);}void test4(){ int arr[]={1,2,3,4,5,6,7,8,9}; muliptlc3front(arr,9); printArr(arr,9);}int main(){ cout<<"test1:"<<endl; test1(); cout<<"test2:"<<endl; test2(); cout<<"test3:"<<endl; test3(); cout<<"test4:"<<endl; test4(); system("pause"); return 0;}
结果
0 0
- 【面试题】剑指offer14
- 【面试题】剑指offer14--调整一组数据使得奇数位 位于偶数位的前面
- 剑指Offer14 调整数组顺序使奇数位于偶数前面
- 剑指offer14--将两个有序链表合并
- 剑指offer14——调整偶数与奇数的位置
- 剑指offer14:将数组奇数移到偶数前面
- 剑指Offer14:调整数组顺序使奇数位于偶数前面
- 剑指offer 面试题
- 【面试题】剑指offer10
- 【面试题】剑指offer11
- 剑指offer面试题
- 【面试题】剑指offer18
- 【面试题】剑指offer20
- 【面试题】剑指offer21
- 剑指offer面试题总结
- 剑指offer面试题06
- 剑指offer面试题 04
- 剑指offer 面试题07
- Android进入设置中应用对应的详情界面
- scala 的collection
- Codeforces Round #403 C. Underground Lab(脑洞)
- 数据业务建立流程之常规APN参数的创建
- 对个geek青年的状态机,查表纯C实现的代码修改
- 【面试题】剑指offer14
- Linux环境测试管道容量
- (11) spring boot使用jsp实例
- 虚拟机编译webrtc
- 耦合
- 难于捉摸的经络系统?
- 国嵌嵌入式学习笔记-链接器脚本语法格式
- AC自动机模板
- WebSocket原理