用雜湊演算法將陣列轉換到約簡形式 (C++)
本教程將討論使用雜湊演算法將陣列轉換到約簡形式的程式。
為此,將提供一個數組。我們的任務是將給定陣列轉換成其約簡形式,使其僅包含範圍為 0 到 n-1 的元素。
示例
#include <bits/stdc++.h> using namespace std; //converting array to its reduced form void convert(int arr[], int n){ // copying the elements of array int temp[n]; memcpy(temp, arr, n*sizeof(int)); sort(temp, temp + n); //creating a hash table unordered_map<int, int> umap; int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; //putting values in the hash table for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } void print_array(int arr[], int n) { for (int i=0; i<n; i++) cout << arr[i] << " "; } int main(){ int arr[] = {10, 20, 15, 12, 11, 50}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Given Array :\n"; print_array(arr, n); convert(arr , n); cout << "\nConverted Array:\n"; print_array(arr, n); return 0; }
輸出
Given Array : 10 20 15 12 11 50 Converted Array: 0 4 3 2 1 5
廣告