144.Interleaving Positive and Negative Numbers-交错正负数(中等题)
来源:互联网 发布:excel跨表格数据加法 编辑:程序博客网 时间:2024/06/05 17:45
交错正负数
题目
给出一个含有正整数和负整数的数组,重新排列成一个正负数交错的数组。
注意事项
不需要保持正整数或者负整数原来的顺序。样例
给出数组[-1, -2, -3, 4, 5, 6],重新排序之后,变成[-1, 5, -2, 4, -3, 6]或者其他任何满足要求的答案
挑战
原地完成,没有额外的空间
题解
本题若要得到合理的答案,则数组中正负数的个数要么相等,要么比另一种数最多大1个。而题目没有保证正负数个数相等,所以需对数组进行预处理(数组长度为偶数时无需预处理),使得当正(负)数多时,数组第一个数为正(负)。
至于交错正负数的处理就很简单了,双指针遍历即可。
class Solution { /** * @param A: An integer array. * @return: void */ public void rerange(int[] A) { if (A.length % 2 == 1) { int count = 0; int plus = 0; int minus = 0; for (int i=0;i<A.length;i++) { count += A[i] > 0 ? 1 : -1; plus = A[i] > 0 ? i : plus; minus = A[i] < 0 ? i : minus; } int i = count > 0 ? plus : minus; swap(A,i,0); } range(A); } private void range(int[] A) { int left = 0; while (left + 1 < A.length) { if (A[left] * A[left+1] < 0) { left++; } else { int j = A.length-1; while (left < j) { if (A[left] * A[j] < 0) { swap(A,left+1,j); left++; break; } j--; } } } } private void swap(int[] A, int a, int b) { int tmp = A[a]; A[a] = A[b]; A[b] = tmp; }}
Last Update 2016.10.17
0 0
- 144.Interleaving Positive and Negative Numbers-交错正负数(中等题)
- *[Lintcode]Interleaving Positive and Negative Numbers 交错正负数
- 代码面试题:Interleaving Negative and Positive Numbers 正负交替
- Interleaving Positive and Negative Numbers
- Interleaving Positive and Negative Numbers
- Lintcode - Interleaving Positive and Negative Numbers
- [leetcode]Interleaving Positive and Negative Numbers
- lintcode:Interleaving Positive and Negative Numbers
- LintCode Interleaving Positive and Negative Numbers
- Lintcode144 Interleaving Positive And Negative Numbers solution 题解
- LintCode-交错正负数
- 交错正负数
- LintCode 交错正负数
- 题目:交错正负数
- 交错正负数
- 交错正负数
- lintcode --交错正负数
- LintCode:交错正负数
- 【转】JVM简介、介绍
- 《Understanding ECMAScript 6》——Introduction
- 测试姓名性别LOL人品运气Android代码实现闲来无事练练手^_^
- python:type语句与列表操作函数
- 基于OpenCV的条形码区域检测(一)
- 144.Interleaving Positive and Negative Numbers-交错正负数(中等题)
- Django笔记(1)新建项目
- 习题15--读取文件
- orcal安装过程中遇到问题: 未找到文件
- YESLAB阿彭版CCNP Security ASA 防火墙精讲视频课程
- RxJava过滤操作符实例
- 概述
- 麦子学院自动化测试-selenium视频教程
- SQL 数据库 学习 022 查询-05 top 的用法 --- 最前面的若干个记录