存在一個數列的某種排列。如今已知數列中每一個數的大小 arr1 ,和每一個數以前有多少個比它自身小的數 arr2,要求恢復出原來的排列。保證數列中的元素兩兩不等。node
先將全部數按從大到小的順序排列,而後從最大的開始插入到線段樹中。對於區間 [l,mid],[mid,r]。知足[l,mid]中未被填充的數字比比它自身小的數的個數大,則繼續搜索左區間,反之搜索右區間。填充,更新便可。時間複雜度爲O(nlogn)。面試
本題主要考察了快速排序與線段樹的基本操做。數列中有 n 個數,將這 n 個數從大到小排序。線段樹維護數組 [1, n],1 表明未被佔用,0 表明佔用,那麼初始數組 [1, n] 所有爲 1。在處理第 i 大的數時,前 i - 1 個數已經被處理過了,因此只須要尋找 [1, n] 中前綴和爲 arr2[i] 的第一個位置便可,並將這個位置更新爲 0。一共有 n 個數,每次操做 O(logn),故總時間複雜度爲 O(nlogn)。算法
www.jiuzhang.com/solution/co…數組
/**
* 本參考程序來自九章算法,由 @華助教 提供。版權全部,轉發請註明出處。
* - 九章算法致力於幫助更多中國人找到好的工做,教師團隊均來自硅谷和國內的一線大公司在職工程師。
* - 現有的面試培訓課程包括:九章算法班,系統設計班,算法強化班,Java入門與基礎算法班,Android 項目實戰班,
* - Big Data 項目實戰班,算法面試高頻題班, 動態規劃專題班
* - 更多詳情請見官方網站:http://www.jiuzhang.com/?source=code
*/
class SegmentTree {
public int start, end;
public int sum;
public SegmentTree left, right;
public SegmentTree(int start, int end) {
this.start = start;
this.end = end;
this.left = this.right = null;
}
public SegmentTree(int start, int end, int sum) {
this(start, end);
this.sum = sum;
}
public static SegmentTree build(int start, int end) {
if (start > end)
return null;
if (start == end) {
return new SegmentTree(start, end, 1);
}
SegmentTree node = new SegmentTree(start, end, 1);
int mid = (start + end) / 2;
node.left = build(start, mid);
node.right = build(mid + 1, end);
node.sum = 0;
if (node.left != null) {
node.sum += node.left.sum;
}
if (node.right != null) {
node.sum += node.right.sum;
}
return node;
}
public static int query(SegmentTree root, int k) {
if (root.start > root.end)
return 0;
if (root.start == root.end) {
root.sum = 0;
return root.start;
}
int mid = (root.start + root.end) / 2;
int res = 0;
if (k <= root.left.sum) {
res = query(root.left, k);
} else {
res = query(root.right, k - root.left.sum);
}
root.sum = 0;
if (root.left != null) {
root.sum += root.left.sum;
}
if (root.right != null) {
root.sum += root.right.sum;
}
return res;
}
}
class Num {
int val; //The value of numbers
int cnt; //How many numbers small than itself
Num(int val, int cnt){
this.val = val;
this.cnt = cnt;
}
}
class Cmp implements Comparator<Num> {
// delimit how to compare
public int compare(Num a, Num b) {
if (a.val < b.val) {
return 1;
} else {
return -1;
}
}
}
public class Solution {
/**
* @param n: The array sum
* @param arr1: The size
* @param arr2: How many numbers small than itself
* @return: The correct array
*/
static Num[] a = new Num[100000+10];
public int[] getQueue(int n, int[] arr1, int[] arr2) {
int[] ans = new int[n];
// Write your code here
for (int i = 0; i < n; i++) {
a[i] = new Num(arr1[i], arr2[i]);
}
Arrays.sort(a, 0, n, new Cmp());
SegmentTree root = SegmentTree.build(1,n);
for (int i = 0; i < n; i++) {
int pos = SegmentTree.query(root, a[i].cnt+1);
ans[pos-1] = a[i].val;
}
return ans;
}
}複製代碼