Interleaving Positive and Negative Numbers
来源:互联网 发布:vendor.bundle.js 位置 编辑:程序博客网 时间:2024/06/12 10:41
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
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.
java
public class Solution { /* * @param A: An integer array. * @return: nothing */ public void rerange(int[] A) { // write your code here if (A == null || A.length == 0) { return; } Arrays.sort(A); if (A.length % 2 == 0) { int left = 1; int right = A.length - 2; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } else if (A[(A.length - 1) / 2] < 0) { int left = 1; int right = A.length - 1; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } else { sort(A, 0, A.length - 1); int left = 1; int right = A.length - 1; while (left <= right) { swap(A, left, right); left += 2; right -= 2; } } } private void sort(int[] nums, int start, int end) { if (start > end) { return; } int left = start; int right = end; int pivot = nums[(start + end) / 2]; while (left <= right) { while (left <= right && nums[left] > pivot) { left++; } while (left <= right && nums[right] < pivot) { right--; } if (left <= right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } sort(nums, start, right); sort(nums, left, end); } private void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; }}
阅读全文
0 0
- 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
- 代码面试题:Interleaving Negative and Positive Numbers 正负交替
- *[Lintcode]Interleaving Positive and Negative Numbers 交错正负数
- Lintcode144 Interleaving Positive And Negative Numbers solution 题解
- 144.Interleaving Positive and Negative Numbers-交错正负数(中等题)
- 1002 Positive and Negative
- 【HDU5183】Negative and Positive (NP)
- Counting positive and negative number and computing the average of numbers
- True Positive,True Negative,False Positive and False Negative
- True Positive,True Negative,False Positive and False Negative
- hdu 5183 Negative and Positive (NP)
- HDU 5183 Negative and Positive (NP)
- hdu5138 Negative and Positive (NP) 快速读入
- [HDU 2089] 不要62 数位DP(记忆化搜索)
- 判断两个IP是否在同一网段
- python中,用input()输入一个整数
- Ubuntu14.04更新软件校验签名出错
- java编写菱形
- Interleaving Positive and Negative Numbers
- python关于argparse模块的学习内容
- 有根树的同构vijos
- Linux-Ubuntu软件的安装方法
- 拷贝构造与拷贝赋值
- 信息系统开发思维导图
- Error Domain=NSURLErrorDomain Code=-1100 "(null)"
- MATLAB编译C++问题(MEX文件)
- linux--基本指令