C++ 求数组中每个元素的逆序数

已知数组nums,求新数组count,count[i]代表了在nums[i]右侧比nums[i]小的元素个数。

例如:
nums=[5,2,6,1], count = [2,1,1,0];
nums=[6,6,6,1,1,1], count=[3,3,3,0,0,0];
nums=[5,-7,9,1,3,5,-2,1], count=[5,0,5,1,2,2,0,0];

#include
#include
struct BSTNode
{
 int val;
 int count;
 BSTNode* left;
 BSTNode* right;
 BSTNode(int x) : val(x), left(NULL), right(NULL), count(0) {};
};
void BST_insert(BSTNode * node, BSTNode *insert_node,int &count_small)
{
 if (insert_node->val<=node->val)
 {
  node->count++;
  if (node->left)
  {
   BST_insert(node->left, insert_node, count_small);
  }
  else
  {
   node->left = insert_node;
  }
 }
 else
 {
  count_small += node->count + 1;
  if (node->right)
  {
   BST_insert(node->right, insert_node, count_small);
  }
  else
  {
   node->right = insert_node;
  }
 }
}
class Solution
{
public:
 Solution(){}
 ~Solution(){}
 std::vector<int> count_smaller(std::vector<int> &nums)
 {
  std::vector<int> result;
  std::vector<int> count;
  std::vector<BSTNode*> node_vec;
  for(int i=nums.size()-1; i>=0; i--)
  {
   node_vec.push_back(new BSTNode(nums[i]));
  }
  count.push_back(0);       //这步容易漏掉
  for (int i = 1; i < node_vec.size(); i++)
  {
   int count_small = 0;
   BST_insert(node_vec[0], node_vec[i], count_small);
   count.push_back(count_small);
  }
  for (int  i =node_vec.size()-1; i >=0; i--)
  {
   delete node_vec[i];
   result.push_back(count[i]);
  }
  return result;
 }
};
int main()
{
 int test[] = { 5,-7,9,1,3,5,-2,1 };
 std::vector<int> nums;
 for (int i = 0; i < sizeof(test)/sizeof(test[0]); i++)
 {
  nums.push_back(test[i]);
 }
 Solution solve;
 std::vector<int> result = solve.count_smaller(nums);
 for (int i = 0; i < result.size(); i++)
 {
  printf("[%d]",result[i]);
 }
 printf("\n");
 return 0;
}

运行结果为:

[5][0][5][1][2][2][0][0]

你可能感兴趣的:(C++ 求数组中每个元素的逆序数)