fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int solve(vector<int>& a , int k){
  5. int n = a.size();
  6. int minLen = INT_MAX;
  7. unordered_map<int,int>mpp;
  8. mpp[a[0]] = 0;
  9. for(int j=1;j<n;j++){
  10. int target = k - a[j];
  11. if(mpp.count(target)){
  12. int len = j-mpp[target]+1;
  13. minLen = min(minLen,len);
  14. }
  15. mpp[a[j]] = j;
  16. }
  17. return (minLen==INT_MAX)? -1 : minLen;
  18. }
  19.  
  20. int main() {
  21. int n;
  22. cin>>n;
  23. vector<int>a(n);
  24. for(int i=0;i<n;i++){
  25. cin>>a[i];
  26. }
  27. int k;
  28. cin>>k;
  29.  
  30. cout<<solve(a,k);
  31. return 0;
  32. }
Success #stdin #stdout 0.01s 5288KB
stdin
9
5 6 7 8 10 4 3 2 1
8
stdout
7