-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_217_contains_duplicate.cpp
109 lines (86 loc) · 2.34 KB
/
leetcode_217_contains_duplicate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// https://leetcode.com/problems/contains-duplicate/
// https://youtu.be/3OamzN90kPg
// brute force has O(N2) complexity
// solve is sorting and lookup O(1)
#include <iostream>
#include <vector>
using namespace std;
// Solution using iterator slower than Solution_element_index_O1
class Solution_iterator_O1 {
public:
bool containsDuplicate(vector<int>& nums) {
vector<int>::iterator fixed;
vector<int>::iterator move;
sort(nums.begin(), nums.end());
bool ret = false;
if(nums.size() > 0)
{
for (fixed = nums.begin(),
move = fixed+1;
fixed <= nums.end()-2,
move <= nums.end()-1;
fixed++,
move++)
{
if(*move == *fixed)
{
return true;
}
}
}
return ret;
}
};
// Solution using element access fastest using O(n)
class Solution_element_index_O1 {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
bool ret = false;
int i,j;
if(nums.size() > 0)
{
for (i = 0, j=i+1; i<=nums.size()-2, j<=nums.size()-1; i++,j++)
{
if(nums[i] == nums[j])
{
return true;
}
}
}
return ret;
}
};
// solution using brute force : time limite exceeded O(2)
class Solution_iterator_bruteForce_02 {
public:
bool containsDuplicate(vector<int>& nums) {
vector<int>::iterator fixed;
vector<int>::iterator move;
sort(nums.begin(), nums.end());
bool ret = false;
if(nums.size() > 0)
{
for (fixed = nums.begin(); fixed <= nums.end()-2; fixed++)
{
for(move = fixed+1; move <= nums.end()-1; move++)
{
if(*move == *fixed)
{
return true;
}
}
}
}
return ret;
}
};
int main(void)
{
vector<int> nums = {0,4,5,0,3,6};
//{1,5,-2,-4,0};
//{1,2,3,1};
Solution mSln;
mSln.containsDuplicate(nums);
return 0 ;
}