Journey of LeetCode|DAY 5
Preface
This is a new day to start my Hash Table journey.
Learn something new and keep reviewing what I learnt before.
1. Valid Anagram
LeetCode Link: 242. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Analysis and Solution
Hash Table
Array is a simple Hash Table, which can help us to save the time to solve problems.
Define an array to save 26 values=0.
Traverse s and t, use the ASCII of per letter to calculate with ASCII of “a”, get an index which is the location of the array then value of index +1(value of s) or -1(value of t).
Traverse array, if per value =0, bool returns true, or false.
LeetCode C++ as followings Hash Table
class Solution {
public:
bool isAnagram(string s, string t) {//bool only indicates YES or NO
int Hash[26] = {0};//define a hash table and initial value=0;26 letters
for (int i = 0; i < s.size(); i++) {//traverse s
Hash[s[i] - 'a']++;//use the ASCII of per letter to calculate with ASCII of a,get an index which is the location of the hash table,and then value of index +1
}
for (int i = 0; i < t.size(); i++) {//traverse t
Hash[t[i] - 'a']--;//use the ASCII of per letter to calculate with ASCII of a,get an index which is the location of the hash table,and then value of index -1
}
for (int i = 0; i < 26; i++) {//traverse hash table
if (Hash[i] != 0) {//if per value of whole table exists value !=0,which means that s or t has more or less elements,s!=t
return false;
}
}
// if per value of table =0,s and t are Valid Anagram
return true;
}
};
2. Intersection of Two Arrays
LeetCode Link: 349. Intersection of Two Arrays
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Analysis and Solution
Unordered Set
Set of Hash Table:
- std::set
- std::multiset
- std::unordered_set
Unordered set can delete reduplicated value automatically
Define an unordered set to save the result
Convert the nums to unordered set
Traverse nums2 if find element appeared in the set
Save the element in the result.
LeetCode C++ as followings Unordered Set
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set; // define an unordered_set to save the result;set can delete reduplicated value automatically
unordered_set<int> nums_set(nums1.begin(), nums1.end());//convert the nums to unordered_set,and delete reduplicated value automatically
for (int num : nums2) {//for loop
//int num;
//for (int i=0;i<nums2.length;i++)
//{num=nums2[i]}
// found element of nums2,have appeared in nums_set,too,which means that is an intersection of two arrays.
if (nums_set.find(num) != nums_set.end()) {
//find(key):find the element called key,if found,return cons_iterator points to this element, or return iterator same as end()
//end():return an iterator points to last element
//The map::find() is a built-in function in C++ STL that returns an iterator or a constant iterator that refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end()
result_set.insert(num);//save(insert) the num to result
}
}
return vector<int>(result_set.begin(), result_set.end());//return the whole result
}
};
Array
Array can be used here Since change happened
- 1 <= nums1.length, nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 1000
Define an unordered_set
Define an Array
Record per element of the nums1 in the array
Assign 1 here if recored.
Traverse nums2, insert it in the result if element appeared again
LeetCode C++ as followings Array
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set; // define an unordered_set to save the result;set can delete reduplicated value automatically
int hash[1005] = {0}; // initial value=0
for (int num : nums1) { // record per element of the nums1 in the hash array
//int num;
//for (int i=0;i<nums1.length;i++)
//{num=nums1[i]}
hash[num] = 1;//assign 1 to this node
}
for (int num : nums2) { // record per element of the nums2 in the hash array
//int num;
//for (int i=0;i<nums2.length;i++)
//{num=nums2[i]}
if (hash[num] == 1) {//which means it is an intersection of the two arrays
result_set.insert(num);//save it in the result
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
3. Happy Number
LeetCode Link: 202. Happy Number
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Analysis and Solution
Unordered Set
Firstly, get the sum of every single number of this value, to verify if it is a loop in the next process
Secondly, if sum = 1, it is a right outcome; if sum was found in the set again,which means that is a loop, return false
LeetCode C++ as followings Unordered Set
class Solution {
public:
// get the sum of every single number of this value
int getSum(int n) {//define a getSum function
int sum = 0;//initial sum=0
while (n) {//while loop
sum += (n % 10) * (n % 10);//sum=sum+(n % 10) * (n % 10)
n /= 10;//n=n/10
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> set;//define an unordered set
while(1) {//while loop
int sum = getSum(n);//call the function
if (sum == 1) {
return true;
}
// it is a loop if found sum again,return false at once
if (set.find(sum) != set.end()) {//The map::find() is a built-in function in C++ STL that returns an iterator or a constant iterator that refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end()
return false;
} else {
set.insert(sum);//insert sum
}
n = sum;//while loop n next
}
}
};
4. Two Sum
LeetCode Link: 1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Analysis and Solution
STD::Unordered_Map
LeetCode C++ as followings std::unordered_map
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map <int,int> map;//define a hash map,
for(int i = 0; i < nums.size(); i++) {
// traverse element for now,and find if it has a match key in the map
auto iter = map.find(target - nums[i]);//auto is a type of variation,define value automatically;iter was defined as INT by (target - nums[i]);
if(iter != map.end()) {//
return {iter->second, i};//the next of iter
}
// if not found match,insert the element and index into map
map.insert(pair<int, int>(nums[i], i)); //The pair container is a simple container defined in <utility> header consisting of two data elements or objects.
}
return {};
}
};