Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 1. i. Description of the problem ii. Algorithm of the following codes (both methods) iii. Analyze the running time of each step of the algorithms (both methods) Method 1: class Solution { public: bool containsDuplicate(vector& nums) { int n= nums.size(); sort(begin(nums), end(nums)); for (int i=1; i& nums) { int n = nums.size(); set s; for (int i=0; i
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
1.
i. Description of the problem
ii.
iii. Analyze the running time of each step of the algorithms (both methods)
Method 1:
class Solution {
public:
bool containsDuplicate(
int n= nums.size();
sort(begin(nums), end(nums));
for (int i=1; i<n; i++)
{
if (nums[i] == nums[i-1])
{
return true;
}
}
return false;
}
};
Method 2:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int n = nums.size();
set<int> s;
for (int i=0; i<n; i++)
{
if (s.count(nums[i]))
{
return true;
}
s.insert(nums[i]);
}
return false;
}
};
Trending now
This is a popular solution!
Step by step
Solved in 4 steps