问题描述
我在试图弄清楚如何严格计算表中键的数量时遇到了麻烦,不包括边界键。我的代码似乎计算了包括边界键在内的键。如果您能帮助我解决这个问题,我将不胜感激。
代码:
public int countRangeStrict(Key key1,Key key2) {
if (key1.compareto(key2) == 0) return 0;
if (contains(key2)) return rank(key2) - rank(key1) + 1;
else return (rank(key2) - rank(key1));
}
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException();
int lo = 0;
int hi = N-1;
while (lo<=hi){
int mid = lo + (hi - lo) / 2;
int temp = key.compareto(this.key[mid]);
if (temp < 0) hi = mid - 1;
else if (temp > 0 ) lo = mid + 1;
else return mid;
}
return lo;
}
Output:
countRangeStrictTest: Correct Keys: BEIoU,key1: A key2: Z actual: 5 expected: 5
countRangeStrictTest: *Error* Keys: BEIoU,key1: Z key2: A actual: -5 expected: 5
countRangeStrictTest: Correct Keys: BEIoU,key1: J key2: N actual: 0 expected: 0
countRangeStrictTest: *Error* Keys: BEIoU,key1: C key2: O actual: 3 expected: 2
countRangeStrictTest: *Error* Keys: BEIoU,key1: B key2: P actual: 4 expected: 3
还有一点,key1和key2可能没有顺序,但是我的代码只考虑key1为下边界,key2为上边界。我该怎么做才能让代码严格计算边界之间的键,并且边界不需要按顺序排列?
提前致谢!
解决方法
测试 #2: 键被反转,您的代码没有检测到。您需要检查 const emailRegex = /^[^@ ]+@[^@ ]+\.[^@ ]+$/
const result1 = emailRegex.test('hello@there.com')
console.log(result1) // true
const result2 = emailRegex.test('hel@lo@there.com')
console.log(result2) // false
并交换密钥。
测试 #4 和 #5:您说“排除边界键”,但是您的 key1.compareTo(key2) > 0
方法被明确编码为include 两个边界键。
这意味着你的代码应该是这样的:
countRangeStrict()