Careercup - Google面试题 - 4699414551592960 - zhuli19901106 - 博客园


Careercup - Google面试题 - 4699414551592960 - zhuli19901106 - 博客园
we have a random list of people. each person knows his own height and the number of tall people in front of him. write a code to make the equivalent queue.  for example :  input: <"Height","NumberOfTall","Name">,  <6,2,"A">,<1,4,"B">,<11,0,"C">,<5,1,"D">,<10,0,"E">,<4,0,"F">  output: "F","E","D","C","B","A" --> end of queue
题目:有一队人正在排队,告诉你每个人的姓名、身高(目前默认都不相同),以及他/她所看到的前面比他高的人。请你计算出这个队伍里各个人的顺序。
解法:从最矮的人入手。对于最矮的人,他所看到的所有人都比他高,所以如果他看到有K个人比他高,那么他一定排在K + 1名。我的代码是当时琢磨了很久,采用树状数组写出来的。此处的树状数组提供快速修改区间、查询单个元素的能力,能做到对数时间。现在居然已经忘了当时的具体思路。总体思想是先按身高升序排序,然后逐个确定每个人在队列里的位置。关键的一点:每次都只能确定当前最矮的人排在哪儿。树状数组中维护的值c[i]的意义,是记录当前位置的前面有多少个比它高。其中还有个方法用到二分搜索,所以整体复杂度是比较奇怪的O(n * log(n) +  n * log^2(n)) = O(n * log^2(n))。

  8 struct Person {
  9     int height;
 10     int taller;
 11     string name;
 12     Person(int _height = 0, int _taller = 0, string _name = ""): 
 13         height(_height), taller(_taller), name(_name) {};
 14     bool operator < (const Person &other) {
 15         return this->height < other.height;
 16     };
 17     
 18     friend ostream& operator << (ostream &cout, const Person &p) {
 19         cout << '<'<< p.name << p.height << '>';
 20         return cout;
 21     };
 22 };
 23 
 24 template <class T>
 25 class BinaryIndexedTree {
 26 public:
 27     BinaryIndexedTree(int _n = 0): n(_n), v(_n + 1) {};
 28     
 29     int size() {
 30         return n;
 31     };
 32     
 33     void addAll(int x, const T &val) {
 34         while (x >= 1 && x <= n) {
 35             v[x] += val;
 36             x -= lowBit(x);
 37         }
 38     };
 39     
 40     void addInterval(int x, int y, const T &val) {
 41         addAll(x - 1, -val);
 42         addAll(y, val);
 43     };
 44     
 45     void clear() {
 46         v.resize(1);
 47         n = 0;
 48     };
 49     
 50     void resize(int new_n) {
 51         v.resize(new_n + 1);
 52         n = new_n;
 53     }
 54     
 55     T sum(int x) {
 56         T res = 0;
 57         while (x >= 1 && x <= n) {
 58             res += v[x];
 59             x += lowBit(x);
 60         }
 61         
 62         return res;
 63     };
 64     
 65     int lowerBound(const T &val) {
 66         int ll, mm, rr;
 67         
 68         if (n == 0) {
 69             return 0;
 70         }
 71 
 72         T res;
 73         if (val <= (res = sum(1))) {
 74             return 1;
 75         }
 76         if (val > (res = sum(n))) {
 77             return n + 1;
 78         }
 79         
 80         ll = 1;
 81         rr = n;
 82         while (rr - ll > 1) {
 83             mm = (ll + rr) / 2;
 84             res = sum(mm);
 85             if (val > res) {
 86                 ll = mm;
 87             } else {
 88                 rr = mm;
 89             }
 90         }
 91         
 92         return rr;
 93     }
 94 private:
 95     vector<T> v;
 96     int n;
 97     
 98     int lowBit(int x) {
 99         return x & -x;
100     };
101 };
102 
103 int main()
104 {
105     vector<Person> people;
106     vector<int> queue;
107     BinaryIndexedTree<int> bit;
108     int i, j;
109     int n;
110     
111     while (cin >> n && n > 0) {
112         people.resize(n);
113         for (i = 0; i < n; ++i) {
114             cin >> people[i].height >> people[i].taller >> people[i].name;
115         }
116         sort(people.begin(), people.end());
117         bit.resize(n);
118         queue.resize(n);
119         for (i = 1; i <= n; ++i) {
120             bit.addInterval(i, n, 1);
121         }
122         for (i = 1; i <= n; ++i) {
123             j = bit.lowerBound(people[i - 1].taller + 1);
124             queue[j - 1] = i;
125             bit.addInterval(j, n, -1);
126         }
127         for (i = 0; i < n; ++i) {
128             cout << people[queue[i] - 1];
129         }
130         cout << endl;
131         
132         people.clear();
133         queue.clear();
134         bit.clear();
135     }
136     
137     return 0;
138 }

https://moonstonelin.wordpress.com/2016/04/22/reconstruct-tree/
public class Node
{
    public Person Person { get; set; }
    public int LeftSelfCount { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }
    public Node(Person person, int leftSelfCnt)
    {
        this.Person = person;
        this.LeftSelfCount = leftSelfCnt;
        this.Left = null;
        this.Right = null;
    }
}
public class Tree
{
    public Node Root { get; set; }
    public Tree()
    {
        this.Root = null;
    }
    public void Insert(Person p)
    {
        if (this.Root == null)
        {
            this.Root = new Node(p, 1);
        }
        else
        {
            if (p.AheadTallerCount < this.Root.LeftSelfCount)
            {
                this.Root.LeftSelfCount++;
                InsertHelper(this.Root, this.Root.Left, p);
            }
            else
            {
                InsertHelper(this.Root, this.Root.Right, p);
            }
        }
    }
    public void InOrder(Node node, List<Node> result)
    {
        if (node == null)
        {
            return;
        }
        InOrder(node.Left, result);
        result.Add(node);
        InOrder(node.Right, result);
    }
    private void InsertHelper(Node parent, Node child, Person p)
    {
        if (child == null)
        {
            if (p.AheadTallerCount < parent.LeftSelfCount)
            {
                parent.Left = new Node(p, 1);
            }
            else
            {
                parent.Right = new Node(p, 1);
            }
        }
        else
        {
            if (p.AheadTallerCount < child.LeftSelfCount)
            {
                child.LeftSelfCount++;
                InsertHelper(child, child.Left, p);
            }
            else
            {
                InsertHelper(child, child.Right, p);
            }
        }
    }
}
    public void TestReConstructTree()
    {
        ////<6,2,"A">,<1,4,"B">,<11,0,"C">,<5,1,"D">,<10,0,"E">,<4,0,"F">
        Person A = new Person("A", 6, 2);
        Person B = new Person("B", 1, 4);
        Person C = new Person("C", 11, 0);
        Person D = new Person("D", 5, 1);
        Person E = new Person("E", 10, 0);
        Person F = new Person("F", 4, 0);
        List<Person> input = new List<Person>() { A, B, C, D, E, F };
        List<Person> result = ReConstructTree(input);
    }
    public List<Person> ReConstructTree(List<Person> people)
    {
        people.Sort(this.SortByHeight);
        Tree tree = new Tree();
        foreach (Person p in people)
        {
            tree.Insert(p);
        }
        List<Node> list = new List<Node>();
        tree.InOrder(tree.Root, list);
        List<Person> result = new List<Person>();
        foreach (var n in list)
        {
            result.Add(n.Person);
        }
        return result;
    }
    private int SortByHeight(Person p1, Person p2)
    {
        if (p1.Height < p2.Height)
        {
            return 1;
        }
        else if (p1.Height > p2.Height)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
    public void TestCountSmaller()
    {
        int[] nums1 = new int[] { 5, 2, 6, 1 };
        IList<int> result1 = CountSmaller(nums1);
        int[] nums2 = new int[] { 2, 0, 1 };
        IList<int> result2 = CountSmaller(nums2);
    }
https://www.careercup.com/question?id=4699414551592960
https://www.careercup.com/question?id=24532662

Related:
https://moonstonelin.wordpress.com/2016/04/02/restruct-queue/
http://www.1point3acres.com/bbs/thread-154493-1-1.html
restruct queue题目意思大概是这样。一群人在一点商店的门口排好队站着,每个人的身高都不同,到中午了,大家都去吃饭,吃完饭之后回来,要求按照之前的顺序排好队,给的信息是每个人的身高和原来队伍中在其前面有多少个比他高的人。 这轮本身不是很困难,但是楼主第一轮太紧张了,算法搞定后,在coding的时候卡在了插入的环节,国人姐姐很有耐心也帮助了我不少,最后想想,代码还是有点问题。

第一题可以bst吧,bst按照这个节点的位置排序,先从高到低sort,然后根据f(x)插入,f(x)表示x前面有多少个人比他高,同时每个节点维护当前有多少个节点在其左边,这可以在递归时候返回。

第一高的人是root。第二高的人,f(x)值决定是在root的左边还是右边。第n高的人,f(x)最多为n-1,由于我们已经维护了当前每个节点左边多少个节点,所以就知道插入的位置了。这里key point是,比x高的人是在他之前插入tree的,因为我们是按照从高到底插入tree。

bst最后in order traverse就是返回的结果。

但是因为没有balance,所以结果也不一定好哪里去。

Read full article from Careercup - Google面试题 - 4699414551592960 - zhuli19901106 - 博客园

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts