【发布时间】:2019-05-11 05:05:56
【问题描述】:
我在黑客马拉松中遇到了这个问题,但不知道我哪里出错了。
问题陈述是
Count the number of subsequences in an array where the difference of the first and last element is <= K
Each subsequence is contiguous
Input: 11 5 2 15 25
Output: 6
Explanation: {11}, {5}, {2}, {15}, {25}, {5, 2}
我相信他们正在考虑将单个元素作为有效的子序列,所以 我试图返回数组的长度 + 计数。
int getCount(int *a, int n, int k){
sort(a, a + n);
int c = 0;
for(int i=0; i<n; i++){
int j = i + 1;
while(j < n and a[j] - a[i] <= k){
c+=1;
j+=1;
}
}
return n + c;
}
我尝试过排序,但仍然超时!
【问题讨论】:
-
为什么要对输入进行排序?有必要吗?
-
实际上我之前在 geeksforgeeks 上做过一个类似的问题,他们提出了一个关于排序的策略。 geeksforgeeks.org/pairs-difference-less-k
标签: c++ arrays subsequence