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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Contains Duplicate

發布時間:2025/4/16 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Contains Duplicate 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

給定一個整形數組,從中找出是否存在重復元素。可以使用map來實現,遍歷數組,每訪問一個元素,看其是否在map中出現,如已出現過,則存在重復元素,如沒有,則將元素加入到map中。?

class Solution { public:bool containsDuplicate(vector<int>& nums) {map<int, int> temp;for (int i = 0; i<nums.size(); i++) {if(temp.count(nums[i])!=0){return true;}temp[nums[i]]=i; }return false;} };


其他思路:

public class Solution {public boolean containsDuplicate(int[] nums) {Set<Integer> appearedNum = new HashSet<Integer>();for(int i = 0; i < nums.length; i++){if(!appearedNum.contains(nums[i])){appearedNum.add(nums[i]);} else return true;}return false;} }
class Solution { public:bool containsDuplicate(vector<int>& nums) {map<int, int> int_map;for (int i = 0; i<nums.size(); i++) {if(int_map.count(nums[i])){return true;}int_map.insert(pair<int, int>(nums[i], i)); }return false;} };
</pre><p></p><p style="font-family:'Microsoft YaHei'; padding-top:0px; padding-bottom:0px; font-size:14px; color:rgb(63,63,63); line-height:30px">1、哈希法。用一個set記錄所有已經出現過的數字,若出現沖突,則包含重復元素,若不沖突,則不包含重復元素。此方法的時間復雜度為O(n),空間復雜度為O(n)</p><p style="font-family:'Microsoft YaHei'; padding-top:0px; padding-bottom:0px; font-size:14px; color:rgb(63,63,63); line-height:30px"></p><pre code_snippet_id="674894" snippet_file_name="blog_20150525_1_2671361" name="code" class="cpp" style="font-family: 'Microsoft YaHei'; padding: 5px; background-color: rgb(246, 246, 246); border: 1px dotted rgb(170, 170, 170); color: rgb(63, 63, 63); line-height: 30px;"><pre name="code" class="cpp">class Solution { public:bool containsDuplicate(vector<int>& nums) {set<int> s;int len=nums.size();for(int i=0; i<len; i++){if(s.find(nums[i])==s.end()){s.insert(nums[i]);}else{return true;}}return false;} };

2、排序法。現將數組排序,然后掃描一次數組,若出現相鄰的兩個數相同,則包含重復元素,否則沒有。此方法時間復雜度為O(nlogn),空間復雜度為O(1)【取決于排序方法】,不過用leetcode跑出來比1方法要快些,因為1方法建立set需要花費一些時間,也有測試用例的問題。

<pre name="code" class="cpp">class Solution { public:bool containsDuplicate(vector<int>& nums) {std::sort(nums.begin(), nums.end());int len=nums.size();for(int i=1; i<len; i++){if(nums[i-1]==nums[i]){return true;}}return false;} };

#include<iostream> #include<map> using namespace std;int main() {int a[] = { 1, 2, 3, 4, 5, 6,7, 8 };int len = sizeof(a) / sizeof(a[0]);map<int, int> m;bool temp=false;for (int i = 0; i < len; i++){if (m.find(a[i]) == m.end())m[a[i]]=i;else{temp = true;break;}}cout << temp; system("pause");return 0; }

總結

以上是生活随笔為你收集整理的Contains Duplicate的全部內容,希望文章能夠幫你解決所遇到的問題。

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