Day7-HashTable 02
454. 4Sum II
Node:
- Create an
arrAwhich is sum of the Combination ofarr1andarr2, and anarrBwhich is sum of the Combination ofarr3andarr4,- This question will be change to find the
element from arrA + element from arrB = 0;
- This question will be change to find the
- Using Map in JavaScript can indeed be faster than using an Object as a hashtable, especially when dealing with large datasets or frequent insertions and lookups
Time Complexity && Space Complexity
- Time Complexity: O(n^2)
- Space Complexity: O(n^2)
- The worse case, every sum from the
const sum = num1 + num2;inside two layer loop are different every time
- The worse case, every sum from the
1 | var fourSumCount = function(nums1, nums2, nums3, nums4) { |
383. Ransom Note
Node:
magazine.lengthcould equal or more thanransomNote.length
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
- There are only 26 letters
- The size of map wouldn’t increase when the input length incease
1 | var canConstruct = function(ransomNote, magazine) { |
15. 3Sum
Node:
- Use hashtable will be too complex and will get time exceed error for some use cases
- Use three pointers
- i
for(let i = 0; i < nums.length; i++)- when
nums[i] > 0, break - when
i>0 && nums[i]==nums[i-1]continue;
- when
- j:
j=i+1- when
sum < target,j++ - when
sum === 0,j++andwhile(nums[j] === nums[j-1]&&j<k) j++;
- when
- k:
k=nums.length-1- when
sum > target,k-- - when
sum === 0,k--andwhile(nums[k] === nums[k+1] && j < k) k--;
- when
- i
Time Complexity && Space Complexity
- Time Complexity: O(n^2)
- the outer loop: O(n)
- Inside, j and k will iterate the nums one round in total
- Space Complexity: O(1)
1 | var threeSum = function(nums) { |
18. 4Sum
Node:
- Similar as 3sum, just need one more loop
- target could be negative
- Use four pointers
- i
for(let i = 0; i < nums.length; i++)- when
i>0 && nums[i]==nums[i-1]continue;
- when
- j
for(let j = i+1; i < nums.length; j++)- when
j > i+1 && nums[j] == nums[j-1]continue
- when
- k:
k=j+1- when
sum < target,k++ - when
sum === 0,k++andwhile(nums[k] === nums[k-1]&&k<l) k++;
- when
- l:
l=nums.length-1- when
sum > target,l-- - when
sum === 0,l--andwhile(nums[l] === nums[l+1] && k < l) l--;
- when
- i
Time Complexity && Space Complexity
- Time Complexity: O(n^3)
- Space Complexity: O(1)
1 | var fourSum = function(nums, target) { |
- Title: Day7-HashTable 02
- Author: Guoyi
- Created at : 2024-08-30 22:20:50
- Updated at : 2024-12-07 03:58:41
- Link: https://guoyiwang.github.io/Algorithm/Day7-HashTable02/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments