日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

给定一个由n个数字组成的数组,请检查是否存在重复项

發布時間:2025/3/11 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 给定一个由n个数字组成的数组,请检查是否存在重复项 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

This is a searching problem which can be solved using brute force approach. But here we are going to see use of hash table to solve such searching problems at lower time complexity.

這是一個搜索問題,可以使用蠻力方法解決。 但是在這里,我們將看到使用哈希表以較低的時間復雜度解決此類搜索問題。

Algorithm:

算法:

Hash table is a simple and effective data structure to solve searching problems in O(1) time complexity. Hash tables can be easily built using STL in C++.

哈希表是一種簡單有效的數據結構,可以解決O(1)時間復雜度的搜索問題。 哈希表可以使用C ++中的STL輕松構建。

The algorithm to solve the problem:

解決問題的算法:

  • Create hash table.

    創建哈希表 。

  • Set element pointer to 0. (starting from array[0], first element)

    將元素指針設置為0。(從array [0],第一個元素開始)

  • Search for the element in the Hash table.

    在哈希表中搜索元素。

  • If found there is duplicate. Print "duplicate found" & return from program.

    如果發現重復。 打印“發現重復”并從程序返回。

  • Else insert the element to the hash table.

    否則將元素插入哈希表。

  • If end of the array is reached, exit and print "no duplicate found".

    如果到達數組末尾,請退出并打印“找不到重復項” 。

  • Else increase the element pointer and go to step 3 (continue).

    否則,增加元素指針,然后轉到步驟3(繼續)。

  • Time complexity: O(1) for searching hash table, O(n) overall

    時間復雜度: O(1)用于搜索哈希表,總體為O(n)

    Space complexity: O(n) (for creating hash table)

    空間復雜度: O(n)(用于創建哈希表)

    Creating hash table using STL

    使用STL創建哈希表

    Hash table is created using unordered_set in STL.

    哈希表是使用STL中的unordered_set創建的。

    C ++實現 (C++ implementation )

    #include<bits/stdc++.h> using namespace std;void checkDuplicate(unordered_set<int> hash, int* a, int n){for(int i=0;i<n;i++){if(hash.find(a[i])==hash.end()){hash.insert(a[i]);}else{printf("Duplicate found.....\n");return;}}printf("No duplicates found........\n"); }int main(){int n,x,count=0;printf("how many elements do you want in your array\n");scanf("%d",&n);printf("enter elements\n");// dynamic array createdint* a=(int*)(malloc(sizeof(int)*n)); // creating hash tableunordered_set <int> hash; for(int i=0;i<n;i++){scanf("%d",&a[i]);}// function to check duplicate exists or notcheckDuplicate(hash,a,n); return 0; }

    Output

    輸出量

    First run: how many elements do you want in your array 5 enter elements 1 2 3 4 5 No duplicates found........Second run: how many elements do you want in your array 6 enter elements 3 2 1 3 5 6 Duplicate found.....

    翻譯自: https://www.includehelp.com/algorithms/given-an-array-of-n-numbers-check-whether-there-is-any-duplicate-or-not.aspx

    總結

    以上是生活随笔為你收集整理的给定一个由n个数字组成的数组,请检查是否存在重复项的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。