一道使用了翻手算法解答的算法题
来源:互联网 发布:深入浅出mysql百度云 编辑:程序博客网 时间:2024/04/27 09:42
一个未排序整数数组,有正负数,重新排列使负数排在正数前面,并且要求不改变原来的 相对顺序 比如: input: 1,7,-5,9,-12,15 ans: -5,-12,1,7,9,15 要求时间复杂度O(N),空间O(1) 。
#include <stdio.h>#include <stdlib.h>#include <time.h>#define N 10000#define M 20#define DEBUGvoid reverse(int *left, int *right){while (left < right) {int tmp = *left;*left++ = *right;*right-- = tmp;}}void swap_arr(int *lbegin, int *lend, int *rbegin, int *rend){reverse(lbegin, lend);reverse(rbegin, rend);reverse(lbegin, rend);}/**************** Just for Test ******************/int random1(){int isPos, val;static unsigned seed = 1;srand(seed + (unsigned)time(NULL));seed++;isPos = rand() % 10;val = rand() % 1000;return isPos ? val : -val;}int is_true(int arr[]){int i;for (i = 0; i < N; ++i)if (arr[i] >= 0)break;for ( ; i < N; ++i)if (arr[i] < 0)break;return i == N ? 1 : 0;}/**************** Just for Test ******************/int main(){int arr[N];int *lbegin, *lend, *rbegin, *rend;int i;#ifdef DEBUGFILE *fp;fp = fopen("arr_swap.out", "w");if (fp == NULL) {printf("cannot open this file\n");exit (0);}#endiffor (i = 0; i < N; ++i)arr[i] = random1();for (i = 0; i < N; ++i)if (arr[i] >= 0)break;lbegin = &arr[i];for ( ; i < N; ++i) {if (arr[i] < 0) {lend = &arr[i-1];rbegin = &arr[i];for (; i < N; ++i) if (arr[i] >= 0)break;rend = &arr[--i];swap_arr(lbegin, lend, rbegin, rend);lbegin += ((rend - rbegin) / sizeof(int *) + 1);}}#ifdef DEBUGfor (i = 0; i < N; ++i) {if ( (i%M) == (M-1))fputc('\n', fp);fprintf(fp, "%d ", arr[i]);}fclose(fp);#endifif (is_true(arr) == 1)printf("true\n");return 0;}
- 一道使用了翻手算法解答的算法题
- 一道Google算法题的解答
- 翻手算法
- 翻手算法--php实现
- 一道Google算法题的解答 Gray Codex
- 一道算法题,求高手解答!!
- 字符串移位之翻手算法
- 一道算法题的数学分析
- 一道有趣的算法题
- 一道有趣的算法题
- 一道算法题的解析
- 一道小的算法题
- 一道有趣的算法题。。。
- 一道简单的算法题
- 一道简单的算法题
- 曾经做的一道算法题,到目前为止,我觉得是最好的一道算法题了。
- 每天一道算法题——拼音翻译成阿拉伯数字(只有数字拼音)
- 使用python解决的第一道算法题
- 数据结构算法面试题精选及整理-随机数rand7生成rand10函数
- js event.keyCode
- [ASP.net WebForm] GridView的CommandField Button做刪除提示
- 惊喜还是承诺
- 搭建Linux内核代码阅读环境
- 一道使用了翻手算法解答的算法题
- 命名空间-namespace含义
- VC6 下使用 STLPort
- lrzsz工具的安装步骤
- 关于java+多态关键点--动态绑定
- SecureCR文件上传与下载协议和方法
- 如何查看Linux系统的文件类型
- 非插件实现wordpress随机文章
- 确保路径存在的函数 ensurePathExist