1 条题解
-
0
在这个问题中,你可以采用以下方法:首先,将数组排序。
设
ans为答案。那么你有两种情况:- 如果 ,则
ans = a[0] - 1 - 否则,
ans = a[k-1](对于 索引的数组)
然后你需要计算数组 中小于或等于
ans的元素个数,记为cnt。如果
ans < 1或者cnt ≠ k,则输出"-1";否则输出ans。#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n, k; scanf("%d %d", &n, &k); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); sort(a.begin(), a.end()); int ans; if (k == 0) { ans = a[0] - 1; } else { ans = a[k - 1]; } int cnt = 0; for (int i = 0; i < n; ++i) if (a[i] <= ans) ++cnt; if (cnt != k || !(1 <= ans && ans <= 1000 * 1000 * 1000)) { puts("-1"); return 0; } printf("%d\n", ans); return 0; } - 如果 ,则
- 1
信息
- ID
- 6788
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者