[LintCode] Interleaving Positive and Negative Numbers
2015-09-09 09:42
369 查看
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Example
Given
Note
You are not necessary to keep the original order of positive integers or negative integers.
Challenge
Do it in-place and without extra memory.
Example
Given
[-1, -2, -3, 4, 5, 6], after re-range, it will be
[-1, 5, -2, 4, -3, 6]or any other reasonable answer.
Note
You are not necessary to keep the original order of positive integers or negative integers.
Challenge
Do it in-place and without extra memory.
class Solution { public: /** * @param A: An integer array. * @return: void */ void rerange(vector<int> &A) { int n = A.size(); if(n < 3) return; int posNum = 0, negNum = 0, posIdx = 0, negIdx = 1; for(size_t t = 0;t < n;++t){ if(A[t] >= 0) ++posNum; else ++negNum; } if(negNum > posNum){ negIdx = 0; posIdx = 1; } while(posIdx < n && negIdx < n){ while(posIdx < n && A[posIdx] >= 0) posIdx += 2; while(negIdx < n && A[negIdx] < 0) negIdx += 2; if(posIdx < n && negIdx < n) swap(A[posIdx],A[negIdx]); } } };
相关文章推荐
- 12个有趣的C语言面试题及答案
- 提高xcode的编译运行速度的方法
- curl 命令
- mysql修改密码的四种方法
- Eclipse 连接MySQl数据库总结
- 通用拦截器
- finalize()方法调用的时机
- 永远保持可以随时离开的能力
- mybatis foreach 熟悉
- linux调度器(一)——概述
- php排序函数测试
- iOS视图生命周期
- Hibernate – One-to-One example (XML Mapping)
- 三分钟理解Java中字符串(String)的存储和赋值原理
- LeetCode之Basic Calculator II
- mysql基本操作
- UINavigationController 返回上一级,返回根控制器,返回某一级
- TextVIew字体设置
- Python脚本后台运行的几种方式
- 西门子S7-300系列plc和紫金桥软件的通讯