You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
题意:
计算数组中元素的右侧比它小的元素个数
思路:
1、插入排序法:
建立新的有序数组,将原数组中的元素从后向前依次插入到新数组中,每次插入前利用二分法找到元素应该插入的位置,找到位置的下标就是该元素在原数组中右侧比它小的元素的个数。
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) { //记住vector做参数的用法
vector<int> t, res(nums.size()); //t是新的有序数组,res用来保存答案
for (int i = nums.size() - 1; i >= 0; --i) { //从后往前插入元素
int left = 0, right = t.size();
while (left < right) { //二分法查找应插入的位置
int mid = left + (right - left) / 2;
if (t[mid] >= nums[i]) right = mid;
else left = mid + 1;
}
res[i] = right; //保存找到的位置下标
t.insert(t.begin() + right, nums[i]); //插入元素
}
return res;
}
};
2、此外,可以利用C++中STL自带的函数来实现上述代码中的二分搜索部分,简化代码。主要利用了lower_bound()和distance()两个函数。
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
vector<int> t, res(nums.size());
for (int i = nums.size() - 1; i >= 0; --i) {
int d = distance(t.begin(), lower_bound(t.begin(), t.end(), nums[i]));
res[i] = d;
t.insert(t.begin() + d, nums[i]);
}
return res;
}
};
3、二分搜索树
首先构造一棵二分搜索树,稍有不同的地方是我们需要加一个变量smaller来记录已插入结点中比当前节点值小的所有节点的个数。我们每插入一个节点,会判断其与根节点的大小,如果新的节点值小于根节点值,则增加根节点的smaller,并会插入到左子树中,继续递归调用左子节点的insert。如果节点值大于根节点值,则需要递归调用右子节点的insert并加上根节点的smaller,并加1:
class Solution {
public:
struct Node {
int val, smaller; //val 保存结点的值,smaller保存该结点的左子树中结点个数,即到当前时刻插入的元素中比val小的元素的个数
Node *left, *right;
Node(int v, int s) : val(v), smaller(s), left(NULL), right(NULL) {} //结构体构造函数
};
int insert(Node *&root, int v) {
if (!root) return (root = new Node(v, 0)), 0; //逗号表达式,等价于root = new Node(v,0);return 0;如果为空在,则构造新的结点。
if (root->val > v) return root->smaller++, insert(root->left, v);//如果V小于根节点的val,则将根节点中的smaller+1,向左子树遍历,并返回左子树返回的值
else return insert(root->right, v) + root->smaller + (root->val < v ? 1 : 0); //如果v大于根节点的val,则向右子树遍历,返回值中的三项依次代表,右子树中比v小的元素个数,左子树中比v小的元素个数,root中的val是否比v小。
}
vector<int> countSmaller(vector<int>& nums) {
vector<int> res(nums.size());
Node *root = NULL;
for (int i = nums.size() - 1; i >= 0; --i) { //从后向前依次插入原数组的元素构造二叉树,同时保存结果。在插入nums[i]时,树中元素都是num[i]右边的元素。
res[i] = insert(root, nums[i]);
}
return res;
}
};
C++知识点
- 逗号表达式:
逗号表达式的语法为:表达式1,表达式2,…,表达式n
C++顺序计算表达式1,表达式2,…,表达式n的值。
逗号表达式是有值的,逗号表达式的值为最后一个子表达式的值。 - lower_bound()查找第一个不小于某值元素的位置。
- distance()计算两个迭代器之间的距离。