例如,有一个二叉搜索树,其中包含一系列值。在添加新值之前,我需要检查它是否已包含“几乎重复”。我有 Java 解决方案,它只执行下限和上限以及进一步的条件来完成这项工作。
JAVA:给定 a TreeSet,floor()返回该集合中小于或等于给定元素的最大元素;ceiling()返回该集合中大于或等于给定元素的最小元素
TreeSet<Long> set = new TreeSet<>();
long l = (long)1; // anything
Long floor = set.floor(l);
Long ceil = set.ceiling(l);
Run Code Online (Sandbox Code Playgroud)
C#:最接近的数据结构似乎是SortedSet<>. 谁能建议获得输入值的下限和上限结果的最佳方法?
SortedSet<long> set = new SortedSet<long>();
Run Code Online (Sandbox Code Playgroud) 假设您已将2 vectors传递给函数lvalue references。后来您意识到,可以使用递归并vectors使用它们的切片iterators。
难道是一个恰当的策略,如果我继续前进,写一些util功能,利用这些vecotrs作为rvalues?还是我应该以任何方式避免这种情况?
简化模式:
Node* util(vector<int>&& a, vector<int>&& b) {
Node* root = new Node(a[0]);
root->left = util({ a.begin(), a.end() }, { b.begin(), b.end() });
root->right = util({ a.begin(), a.end() }, { b.begin(), b.end() });
return root;
}
Node* main(vector<int>& a, vector<int>& b) {
return util({ a.begin(), a.end() }, { b.begin(), b.end() });
}
Run Code Online (Sandbox Code Playgroud)
实际示例(LeetCode 105):
TreeNode* util(vector<int>&& preorder, vector<int>&& inorder) {
if …Run Code Online (Sandbox Code Playgroud) 这是我现在const string&无法解决的问题:为什么可以分配到nonconst变量并进一步修改?
const string& shorter_s(const string &s1, const string &s2) {
return s1.size() < s2.size() ? s1 : s2;
}
int main() {
const string s1 = "longer", s2 = "short";
string result = shorter_s(s1, s2);
cout << result << endl;
result += "++";
cout << result << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
short
short++
Run Code Online (Sandbox Code Playgroud)
是不是result要引用const string s2对象,不能通过添加来修改"++"?
来自Leetcode Discussion的算法使用二进制搜索树来保存输入数组中的一系列值,以检查此数组是否包含最多不同于t的值,并且它们的索引最多彼此远离k.
JAVA:
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (nums == null || nums.length == 0 || k <= 0) {
return false;
}
final TreeSet<Integer> values = new TreeSet<>();
for (int ind = 0; ind < nums.length; ind++) {
final Integer floor = values.floor(nums[ind] + t);
final Integer ceil = values.ceiling(nums[ind] - t);
if ((floor != null && floor >= nums[ind])
|| (ceil != null && ceil <= nums[ind])) {
return true;
}
values.add(nums[ind]); …Run Code Online (Sandbox Code Playgroud) 我有一个C ++代码,用于计算从具有X,Y坐标的给定点集中可以形成多少个正方形。5点的样本输入如下:
5
0 0
0 2
1 0
2 0
2 2
Run Code Online (Sandbox Code Playgroud)
一个重要的注意事项是,正方形不需要轴对齐。这是一个工作代码,摘自“ codechef.com”:
int N = 5;
std::vector<int> arr_x{0, 0, 1, 2, 2};
std::vector<int> arr_y{0, 2, 0, 0, 2};
int flag1 = 0;
int flag2 = 0;
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
flag1 = 0;
flag2 = 0;
int x1 = arr_x[i], y1 = arr_y[i]; …Run Code Online (Sandbox Code Playgroud)