Alright let's try leetcode again with cpp
blog update
Neetcode 1: Duplicate Integer
Given an integer array nums
, return true
if any value appears more than once in the array, otherwise return false
.
Example 1:
Input: nums = [1, 2, 3, 3]
Output: true
Example 2:
Input: nums = [1, 2, 3, 4]
Output: false
Python Duplicate Integer
Understand: We need to return true if we find more than 1 of any variable. so [1,1,2,3] returns true and [1,2,3,4] returns false
Match: We see this as a simple hash table problem.
~~Plan: Create a hash table that has integers as key and values as incremented amount~~ Plan: Create a set() because we can automatically remove duplicate numbers in this use case. If set() is less than length of original list, return false. Else return true
Return false at the end of our loop... We couldnt find duplicates.
Implement:
class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
hashset = set() # Python can define a set like so
for n in nums: # Create a loop for num in nums
if n in hashset: # Check existence in hashset at O(1)
return True # Return True if already exists
hashset.add(n) # Continue and add element to the set
return False # Finally return False if our loop exits
Result: We successfully return True on duplicates
Evaluation: We return at O(n) speed where the search for the integer within the hashset is of course at O(1) search.
C++ Duplicate Integer
Understand:
- Again, we have an array of nums and need to return true if there's a duplicate.
- C++ has iterator and cannot be easily outputted as a string
class Solution {
public:
bool hasDuplicate(vector<int>& nums) {
// C++ declares unordered set like so
unordered_set<int> s;
// Loop based on size of the nums
for (int i = 0; i < nums.size(); i++) {
// s.find(nums[i]) aka the iterator
// DOES NOT return s.end(),
if (s.find(nums[i]) != s.end()) {
return true; // then the number already exists in the unordered set so let's return true
}
s.insert(nums[i]);
}
return false;
}
};
How to use the video
Video how to
Good Script doesnt directly explain what thomas metzinger tries to say.
Questions you have about those.
Question answering fix script.
2nd part fix script.
Include stuff from FAQ
Discussion, first?
Whether or not scan and copy would kill you?
Stuff people care about. Why people should care?