M面经Prepare: Positive-Negative partitioning preserving order
发布日期:2021-08-21 02:35:28 浏览次数:10 分类:技术文章

本文共 2052 字,大约阅读时间需要 6 分钟。

Given an array which has n integers,it has both positive and negative integers.Now you need sort this array in a special way.After that,the negative integers should in the front,and the positive integers should in the back.Also the relative position should not be changed.eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.

Solution

Time: O(NlogN), space: O(1)/O(logN) depends on iteration/recursion

This can be done in O(nlogn) using divide and conquer scheme. Before starting the algorithm, please see the following observation:

The basic idea of the algorithm is as follows:

1. We recursively ‘sort’ two smaller arrays of size n/2 (here ‘sort’ is defined in the question)
2. Then we spend \theta(n) time merging the two sorted smaller arrays with O(1) space complexity.
How to merge?
Suppose the two sorted smaller array is A and B. A1 denotes the negative part of A, and A2 denotes positive part of A. Similarly, B1 denotes the negative part of B, and B2 denotes positive part of B.
2.1. Compute the inverse of A2 (i.e., A2’) in \theta(|A2|) time; compute the inverse of B1 (i.e., B1’) in \theta(|B1|) time. [See observation; the total time is \theta(n) and space is O(1)]
Thus the array AB (i.e., A1A2B1B2) becomes A1A2’B1’B2.
2.2. Compute the inverse of A2’B1’ (i.e., B1A2) in \theta(|A2|) time. [See observation; the total time is \theta(n) and space is O(1)]
Thus the array A1A2’B1’B2 becomes A1B1A2B2. We are done.

Time complexity analysis:

T(n) = 2T(n/2) + \theta(n) = O(nlogn)

1 package ArrayMergeSort; 2 import java.util.*; 3  4 public class Solution3 { 5     public void rearrange(int[] arr) { 6         if (arr==null || arr.length==0) return; 7         rearrange(arr, 0, arr.length-1); 8     } 9     10     public void rearrange(int[] arr, int l, int r) {11         if (l == r) return;12         int m = (l+r)/2;13         rearrange(arr, l, m);14         rearrange(arr, m+1, r);15         merge(arr, l, m+1, r);16     }17     18     public void merge(int[] arr, int s1, int s2, int e) {19         int findPos1 = s1, findPos2 = s2;20         while (findPos1

 

转载地址:https://blog.csdn.net/weixin_33708432/article/details/86323091 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:进程间通信(IPC)介绍
下一篇:Android获取 应用程序大小,数据大小,缓存大小

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月14日 00时39分20秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章