44. Interleaving Positive and Negative Numbers (题目链接)
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Example
Example 1
Input : [-1, -2, -3, 4, 5, 6]
Outout : [-1, 5, -2, 4, -3, 6]
Explanation : any other reasonable answer.
Challenge
Do it in-place and without extra memory.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
思路:双指针
class Solution:
"""
@param: A: An integer array.
@return: nothing
"""
def rerange(self, A):
# write your code here
if len(A) <= 1:
return A
neg_i, pos_i = 0, 1
cnt_neg = 0
for num in A:
if num < 0:
cnt_neg += 1
if cnt_neg < (len(A) - cnt_neg):
pos_i, neg_i = 0, 1
while pos_i < len(A) and neg_i < len(A):
while pos_i < len(A) and A[pos_i] > 0:
pos_i += 2
while neg_i < len(A) and A[neg_i] < 0:
neg_i += 2
if pos_i < len(A) and neg_i < len(A):
A[pos_i], A[neg_i] = A[neg_i], A[pos_i]
pos_i += 2
neg_i += 2