Day6-HashTable 01
242. Valid Anagram
Node:
- Could also use array, since there are only 26 letters
- every letter index is char.charCodeAt() - “a”.charCodeAt();
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
- map’s size is determined by the number of unique characters in “s”, which max is 26
- map’s size is constant and not grow up with the size of input “s”
1 | var isAnagram = function(s, t) { |
349. Intersection of Two Arrays
Node:
Time Complexity && Space Complexity
- Time Complexity: O(n+m)
- Space Complexity: O(n)
1 | var intersection = function(nums1, nums2) { |
202. Happy Number
Node:
- Key: there will be same number(n) if it will be a endless loop
- getSum
1
2
3
4
5
6
7
8const getSum = (n)=>{
let sum = 0;
while(n>0){
sum += (n%10) * (n%10);
n = Math.floor(n/10);
}
return sum;
}- Rather than transfer number to string and split and sum by digit one by one, the getSum use mod and divide is a good way
Time Complexity && Space Complexity
Time Complexity: log(n)
- loop * time complexity of getSum
- loop is the length of cycle, which should be a small constant number
- getSum: log(n)
Space Complexity: log(n)
- cache: store the unique sum of the squares of digits
Max number999 => 243 => 29
You can try 9999, 999999
getSum: will be called a maximum of O(log n) times. Because log10 n is the number of digits.
isHappy: will be called a maximum of 9^2 per digit. This is the max we can store in the hash set before we find a cycle or terminate.
Use Recursive
1 | var isHappy = function(n) { |
Use while(true)
1 | var isHappy = function(n) { |
1. Two Sum
Node:
- when save to map, use nums[i]
- when check whether exist in the map, use target-nums[i]
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
1 | var twoSum = function(nums, target) { |
- Title: Day6-HashTable 01
- Author: Guoyi
- Created at : 2024-08-28 22:16:49
- Updated at : 2024-12-07 03:58:41
- Link: https://guoyiwang.github.io/Algorithm/Day6-HashTable01/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments