• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: Interleaving Positive and Negative Numbers

Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Note
You are not necessary to keep the original order or 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 legal answer.

Challenge
Do it in-place and without extra memory.

这道题没有给出正数、负数谁多谁少,所以需要先统计数量,数量多的要包着数量少的,然后数组尾部全是数量多的数

 1 class Solution {
 2     /**
 3      * @param A: An integer array.
 4      * @return an integer array
 5      */
 6     public int[] rerange(int[] A) {
 7         // write your code here
 8         int posNum = 0, negNum = 0;
 9         for (int elem : A) {
10             if (elem < 0) {
11                 negNum++;
12             }
13             else {
14                 posNum++;
15             }
16         }
17         int posInd = 1, negInd = 0;
18         if (posNum > negNum) {
19             negInd = 1;
20             posInd = 0;
21         }
22         while (posInd<A.length && negInd<A.length) {
23             while (posInd < A.length && A[posInd] > 0) {
24                 posInd += 2;
25             }
26             while (negInd < A.length && A[negInd] < 0) {
27                 negInd += 2;
28             }
29             if (posInd<A.length && negInd<A.length) {
30                 swap(A, posInd, negInd);

33 } 34 } 35 return A; 36 } 37 38 public void swap(int[] A, int l, int r) { 39 int temp = A[l]; 40 A[l] = A[r]; 41 A[r] = temp; 42 } 43 }

 

posted @ 2015-03-05 06:14  neverlandly  阅读(1094)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3