1. 程式人生 > >Java總雜湊表的運用,判斷一個數組中是否存在相同的元素之間的距離在k以內!

Java總雜湊表的運用,判斷一個數組中是否存在相同的元素之間的距離在k以內!

Check if a given array contains duplicate elements within k distance from each other

用雜湊表,複雜度O(n),直接巢狀迴圈複雜度O(n*k)。
import java.io.BufferedInputStream;
import java.util.HashSet;
import java.util.Scanner;

public class Main {
    static boolean checkDuplicateWithinK(int arr[], int k) {
        HashSet<Integer> set = new HashSet<>();
        for(int i = 0; i < arr.length; ++i) {
            if(set.contains(arr[i])) {
                return true;
            }
            set.add(arr[i]);
            if(i >= k) {
                set.remove(arr[i-k]);
            }
        }
        return false;
    }
    public static void main(String []args) {
        int T, n, k;
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        while (cin.hasNext()) {
            T = cin.nextInt();
            while (T-- != 0) {
                k = cin.nextInt();
                n = cin.nextInt();
                int arr[] = new int[n];
                for (int i = 0; i < n; ++i) {
                    arr[i] = cin.nextInt();
                }
                if (checkDuplicateWithinK(arr, k) == true) {
                    System.out.println("True");
                } else {
                    System.out.println("False");
                }
            }
        }
    }
}
當然還可以用C++的STL來解決:
#include <bits/stdc++.h>

using namespace std;
const int MAXN = 284;
int arr[MAXN];

int main() {
    ios::sync_with_stdio(false);
    int T, n, k;
    cin >> T;
    while(T--) {
        cin >> k >> n;
        multiset<int> s;
        bool ans = false;
        for(int i = 0; i < n; ++i) {
            cin >> arr[i];
            if(s.find(arr[i]) != s.end()) {
                ans = true;   
            }
            s.insert(arr[i]);
            if(i >= k) {
                s.erase(s.find(arr[i-k]));
            }
        }
        cout << (ans ? "True" : "False") << endl;
    }
    return 0;
}