Advertisement
SalmaYasser

Untitled

Jan 17th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. struct Tree {
  2. int val;
  3. Tree *left;
  4. Tree *right;
  5. int smaller_left;
  6. int dup;
  7.  
  8. Tree( int x) : val(x), left(nullptr), right(nullptr), dup(1), smaller_left(0) {}
  9. };
  10.  
  11.  
  12.  
  13. class Solution {
  14. public:
  15. Tree* insert_order (Tree *root, int val, int count, int &res)
  16. {
  17. if (root == nullptr)
  18. {
  19. Tree* n_node = new Tree(val);
  20. res = count; // extra
  21.  
  22. return n_node;
  23. }
  24.  
  25. if (val > root -> val)
  26. {
  27. int newCount = count + root -> smaller_left + root->dup; // extra
  28. root -> right = insert_order (root -> right, val, newCount ,res);
  29. }
  30. else if (val < root -> val)
  31. {
  32.  
  33. root -> smaller_left++; // extra
  34. root -> left = insert_order (root -> left , val,count ,res);
  35. }
  36. else
  37. {
  38. root -> dup ++; // extra
  39. res = count + root->smaller_left;
  40.  
  41. }
  42. return root;
  43. }
  44.  
  45. vector<int> countSmaller(vector<int>& nums) {
  46.  
  47. int sz = nums.size();
  48.  
  49. vector <int> res (sz,0);
  50.  
  51. if (sz == 0) return {};
  52.  
  53. int cur_res = 0;
  54. Tree *root = insert_order (nullptr, nums[sz - 1],0, cur_res);
  55. res[sz - 1] = cur_res;
  56. for (int i = sz - 2 ; i >= 0; i--)
  57. {
  58. cur_res = 0;
  59. Tree* n_node = insert_order (root, nums[i],0,cur_res);
  60. res[i] = cur_res;
  61. }
  62. return res;
  63. }
  64. };
  65.  
  66.  
  67. class Solution {
  68. public:
  69. vector<int> countSmaller(vector<int>& nums) {
  70. int sz = nums.size();
  71. multiset <int> my_set;
  72. vector <int> res (sz ,0);
  73. for (int i = sz - 1; i >= 0 ; i --)
  74. {
  75. int x = nums[i];
  76. my_set.insert (x);
  77.  
  78. auto it = my_set.lower_bound (x);
  79.  
  80. res[i] = distance (my_set.begin(), it);
  81. }
  82. return res;
  83. }
  84. };
  85.  
  86. /*
  87. time = O(n*logn*n)
  88.  
  89. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement