zoukankan      html  css  js  c++  java
  • 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.

    Analysis:

    We need figure how to address the cases that one kind of numbers is more than the other kind of numbers.

    In LintCode, if postive numbers are more than negtive numbers, the array then start with positive numbers.

    Solution:

     1 class Solution {
     2     /**
     3      * @param A: An integer array.
     4      * @return an integer array
     5      */
     6     public int[] rerange(int[] A) {
     7         if (A.length==0 || A.length==1) return A;
     8         
     9         int posNum = 0;
    10         for (int i : A) if (i>=0) posNum++;
    11         int negP = (posNum>(A.length-posNum)) ? 1 : 0;
    12         int posP = (posNum>(A.length-posNum)) ? 0 : 1;
    13 
    14     int p = A.length-1;
    15     while (negP<A.length && A[negP]<0) negP += 2;
    16     while (posP<A.length && A[posP]>=0) posP += 2;
    17     while (p>=posP || p>=negP){    
    18         if (A[p]<0){
    19             if (negP>=A.length) p--;
    20             else {
    21                 int temp = A[negP];
    22                 A[negP] = A[p];
    23                 A[p] = temp;
    24                 negP += 2;
    25             }
    26         } else {
    27             if (posP >= A.length) p--;
    28             else {
    29                 int temp = A[posP];
    30                 A[posP] = A[p];
    31                 A[p] = temp;
    32                 posP += 2;
    33             }  
    34         }
    35     }
    36 
    37     return A;
    38 
    39      }
    40 }
  • 相关阅读:
    ReactNative: 使用分组列表组件SectionList组件
    ReactNative: 使用刷新组件RefreshControl组件
    ReactNative: 使用开关组件Switch组件
    ReactNative: 使用滑块组件Slider组件
    ReactNative: 使用分段组件SegmentedControlIOS组件
    ReactNative: 使用进度条组件ProgressViewIOS组件
    Swift语言实战晋级
    《Swift开发指南》
    《数据结构与算法JavaScript描述》
    《ASP.NET MVC 5 框架揭秘》
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4187915.html
Copyright © 2011-2022 走看看