[hash series] my roommate was worried that I couldn't sleep in the final exam. I prepared this set of hash topics all night

Posted by phazorRise on Thu, 30 Dec 2021 05:00:23 +0100

⭐ Introduction ⭐ ️
Hello, I'm Zhijie. Today we will bring you a set of special training questions for hash questions. Hash table plays a very important role in data structure. Many students always learn theoretical knowledge and lack practical use. The so-called generals are all killed from the battlefield. If you want to become the great God of Hashi, you have to brush questions crazily. The problem is that many students don't know how to find the right topic to train, and there is no supporting answer analysis. Here I have carefully selected several classic examples of hash for you. The topics are relatively basic, which can make beginners fully feel the charm of hash. Coupled with detailed code thinking analysis, you will gain a lot. It is recommended to collect to prevent missing. You can practice repeatedly. The title is always linked at the end

📒 Blog home page: Persistent blog

🎉 Welcome to pay attention 🔎 give the thumbs-up 👍 Collection ⭐ Leave a message 📝

❤️ : Love Java and algorithm learning and look forward to communicating together!

🙏 The author's level is very limited. If you find an error, please let me know. Thank you!

🌺 If you have questions, you can communicate by private letter!!!          

⭐ Wonderful return visit ⭐ ️

[sum of numbers series] special training of sum of numbers set of questionsPlayback link
[linked list questions series] brush this set of linked list topics to scare the interviewerPlayback link

catalogue

🍍 1. Questions brushing and viewing instructions

🍍 2. Li Ke Hashi, fierce fighting power buckle

                    🐄 1. There are duplicate elements

            🐏 2. There are duplicate elements||

            🐠 3. Valid Letter Words

            🐟  4. Intersection of two arrays

             🐳 5. Happy number

             🐋 6. Ransom letter

             🐬 7. Sum of two numbers

☀️ 3. Hash summary (Title General link)

 

🍍 1. Questions brushing and viewing instructions

You can't really learn any algorithm problem from your own knowledge base if you just don't see it implemented by yourself. Therefore, it is recommended that if you want to pass the title link when you are free, you must try to write it yourself. And even if it is done, we should also find ways to optimize our own code. Even if it is the same method, others may write it more concise and easy to understand. We also need to learn more excellent problem-solving methods with lower complexity. As the saying goes, all roads lead to Rome. I took the far road, but we should also learn the shorter road at the end, otherwise we will still take the farthest Road next time, which is divorced from the essence of learning.         

🍍 2. Li Ke Hashi, fierce fighting power buckle

        🐄 1. There are duplicate elements

Given an integer array, determine whether there are duplicate elements.

If a value exists and appears in the array at least twice, the function returns true. If each element in the array is different, false is returned.

Title Link: There are duplicate elements                

Topic analysis: the name of this topic is already marked by hash. Taking this topic as an introduction to hash is really the best. Hash is a classic space for time (increasing space complexity and reducing time complexity). I also paste the code of sorting practice for comparison.

Method 1: sort

Time complexity O(nlongn): mainly the sorting cost. If it is a simple two-layer for loop, the traversal cost is O(n^2)

Spatial complexity O(nlogn): sorting overhead

class Solution {
    public boolean containsDuplicate(int[] nums) {
            //sort
            Arrays.sort(nums);
            int n=nums.length;        
            //See if adjacent are equal
            for(int i=0;i<n-1;i++){
                if(nums[i]==nums[i+1]){
                    return true;
                }
            }
            return false;
    }
}

Method 2: hash duplication

Complexity O(n):n is the length of nums, which is mainly the time-consuming of the loop

Complexity O(n):n is the length of nums, mainly the overhead of hash. In the worst case, all arrays are put into set

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set=new HashSet<Integer>();
        int n=nums.length;
        for(int i=0;i<n;i++){
            if(!set.contains(nums[i])){
                set.add(nums[i]);
            }else{
                return true;
            }
        }
        return false;
    }
}

         🐏 2. There are duplicate elements||

Given an array of integers and an integer ^ k, judge whether there are two different indexes ^ I ^ and ^ j in the array, so that ^ nums [i] = nums [j], and the absolute value of the difference between I and j ^ is at most k.

Title Link: There are duplicate elements||        

Problem analysis: this problem is the advanced level of the first problem. It has made certain requirements on the requirements of the first problem, which is more suitable for hashing. Because it involves index, we need to convert set into map, key to save the value, and value to save the subscript index.

Method 1: hash duplication

Time complexity O(n): n is the length of nums, which is mainly the time-consuming of the loop. In the worst case, the whole array is traversed.

Spatial complexity O(n): n is the length of nums, mainly the overhead of hash

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        //key stores value and value stores subscript
        Map<Integer,Integer> map=new HashMap<>();
        int n=nums.length;
        for(int i=0;i<n;i++){
            //Without this number, it is stored in the map
            if(!map.containsKey(nums[i])){
                map.put(nums[i],i);
            }else{
                //Not meeting the requirements of the topic
                if(map.get(nums[i])-i>k||i-map.get(nums[i])>k){
                    //Update the subscript to prevent this number from appearing later, which meets the requirements
                    map.put(nums[i],i);                   
                }else{
                    //true is returned if the requirements are met
                    return true;
                }
            }
        }   
        //The end description does not return false
        return false;        
    }
}

          🐠 3. Valid Letter Words

Given two strings s and t, write a function to determine whether t is an alphabetic ectopic word of s.

Note: if each character in , s and t , occurs the same number of times, then , s and t , are called alphabetic words.

Title Link: Valid Letter ectopic words        

Topic analysis: the meaning of this topic is very simple, that is, the letters and frequencies of the string are the same, which is a very classic feature of using hash. But here I want you to know that sorting is the simplest method, and it should be thought of by everyone. As like as two peas, the alphabet can be sorted, and the alphabet can be sorted. If it is a valid letter word, the char[] after sorting must be exactly the same. But you must know. Since it is a hashing session, we must be able to use hashing.

Method 1: convert to char [] sort and compare.

Time complexity O(nlogn): the sorting time is O(nlogn), the traversal world is O(n), and the sum is O(nlogn)

Spatial complexity: O(logn). The sorting API requires O(logn) complexity, and if it is a Java language, due to the immutability of String, you have to use O(n) space to copy the array.

class Solution {
    public boolean isAnagram(String s, String t) {
        //First convert all strings to character arrays
        char[] arr1=s.toCharArray();
        char[] arr2=t.toCharArray();
        //The sort function can also pass in a character array
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        //Arrays has an overridden equals method
        //You can directly compare whether two arrays are exactly the same
        return Arrays.equals(arr2,arr1);
    }
}

Method 2: use an array to map hashes. We should know that the array is also the withdrawal of hash. The index subscript is equivalent to key and the stored value is equivalent to value. We can use a char array with a length of 26 to exist the frequency of each number from a to z, the number of occurrences of each character encountered during traversal of s + 1, and minus 1 when traversing t. If the last array is not all 0, it indicates that it is not a valid Letter ectopic word.

Time complexity O(n): n is the length of a long string, mainly traversal

Space complexity O(1): constant level array consumption is only O(1)

class Solution {
    public boolean isAnagram(String s, String t) {
        //Start with subscript 0 and store a to store the frequency of occurrence of each number
        int[] arr=new int[26];
        //Traversal string s
        for(int i=0;i<s.length();i++){
            //s.charAt(i)-'a' is to find the index subscript corresponding to each character
            arr[s.charAt(i)-'a']++;
        }
        for(int i=0;i<t.length();i++){
            arr[t.charAt(i)-'a']--;
        }
        //Traverse to the description that is not 0, the number of letters is not equal, and false is returned
        for(int i=0;i<arr.length;i++){
            if(arr[i]!=0) return false;
        }
        //No false is returned after traversal, indicating that it is a valid letter, and true is returned
        return true;
    }
}

          🐟  4. Intersection of two arrays

Given two arrays, write a function to calculate their intersection. (I haven't seen such a short topic yet)

Title Link: Intersection of two arrays        

Topic analysis: the more direct method is to traverse nums1. For each element, judge whether the element is in the array nums2 when traversing nums2. Here we only use two sets. The efficiency of hash query elements is O(1), which can help us reduce the time complexity.

Method 1: using HashSet

Time complexity O(n):n is the longer length of nums1 and num2, which is mainly used for traversal with two arrays.

Spatial complexity O(n): n is the length of num1. In the worst case, the whole nums1 is loaded into the set.

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int n1=nums1.length;
        int n2=nums2.length;
        //Used to store one of the arrays
        Set set=new HashSet();
        //The length of the answer will not exceed the length of the short array
        int[] arr=new int[Math.min(n1,n2)];
        for(int i=0;i<n1;i++){
            //set is not allowed to store duplicate elements. Don't worry about whether to store them repeatedly
            set.add(nums1[i]);
        }
        //Used as a pointer to the answer array
        int j=0;
        for(int i=0;i<n2;i++){
            //Judge whether there is in the set. If so, it indicates that both arrays have
            if(set.contains(nums2[i])){
                //Add answer array
                arr[j++]=nums2[i];
                //After adding, it is removed from the set to prevent repeated addition of nums2
                set.remove(nums2[i]);
            }
        }
        //If the answer array is not full, subtract the following
        return Arrays.copyOf(arr,j);
    }       
}

Method 2: sort plus double pointer

In order to obtain the intersection of arrays, we can sort the arrays, point to the beginning of the two arrays with two pointers, and then judge. If they are equal, they are added into the answer array. Before adding, you need to judge whether they have been added, and then the two pointers move one bit to the right.          

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1==null||nums1.length==0||nums2==null||nums2.length==0){
            return new int[0];
        }
        //Sort array
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int[] arr=new int[Math.min(nums1.length,nums2.length)];
        //Double pointer
        int p1=0;
        int p2=0;
        //Pointer used to put the answer array
        int index=0;
        while(p1<nums1.length&&p2<nums2.length){
              if(nums1[p1]==nums2[p2]){
                  //Make sure the answers are not repeated
                  if(index==0||nums1[p1]!=arr[index-1]){
                  arr[index++]=nums1[p1];                 
                  } 
                  //Whether or not you put it into an array, you should++
                  p1++;
                  p2++;           
              }else if(nums1[p1]>nums2[p2]){
                  p2++;
              }else{
                  p1++;
              }  
        }
        return  Arrays.copyOfRange(arr,0,index);
    }
}

             🐳 5. Happy number

Write an algorithm to judge whether a number n is a happy number.

"Happy number" is defined as:

For a positive integer, replace the number with the square sum of the numbers at each position each time.
Then repeat the process until the number becomes 1, or it may be an infinite loop, but it never becomes 1.
If it can be changed to {1, then this number is the number of happiness.
If n is a happy number, return true; If not, false is returned.

Title Link: Happy number           

Topic analysis: we can guess that if a number is not a happy number, it will have a cycle during the operation required by the topic, that is, it will produce repeated numbers. This is a conjecture, but it is true. Its proof needs mathematics to prove, but this conjecture is also easy to think of. If the cycle continues, there will certainly be repeated numbers, resulting in the cycle. In this way, we can use HashSet to judge repetition.

Method 1: hash detection loop

Time complexity O(logn): the time complexity of this topic is not easy to analyze, because we don't know how many times the cycle will occur, so we can't prepare the calculation. We can understand that it is O(logn)

Spatial complexity O(logn): the same as above

class Solution {
    public boolean isHappy(int n) {
        //Used to store the number after each operation
        Set<Integer> set=new HashSet<>();
        //Put n first
        set.add(n);
        //Constant loop, hash detection
        while(true){
            //x saves the value after the n operation
            int x=test(n);
            //It means happy number
            if(x==1){
                return true;
            }
            //The number that does not appear is put into set
            if(!set.contains(x)){
                set.add(x);
            //The number that has appeared indicates that it is not a happy number
            }else{
                return false;
            }
            //Assign x back to n
            n=x;
        }
    }
    //Write an operation method
    public int test(int n){
        int count=0;
        while(n!=0){
            int a=n%10;
            count+=a*a;
            n=n/10;
        }
        return count;
    }
}

             🐋 6. Ransom letter

Give you two strings: ransomNote and magazine. Judge whether ransomNote can be composed of characters in magazine.

If yes, return true; Otherwise, false is returned.

Each character in magazine can only be used once in ransomNote.

Title Link: Ransom letter

Topic: as like as two peas in the first part, the title is just the same as asking for a little change. The code is directly attached to the topic, and only a slight change is made on the first question.

Method: array hash mapping

Time complexity O(n): n is the length of longer strings of ransomNote and magazine. It is mainly the time-consuming of traversal

Space complexity O(1): the consumption of constant level array is regarded as O(1)

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] arr=new int[26];
        for(int i=0;i<ransomNote.length();i++){
            arr[ransomNote.charAt(i)-'a']--;
        }
        for(int i=0;i<magazine.length();i++){
            arr[magazine.charAt(i)-'a']++;
        }
        for(int i=0;i<26;i++){
            if(arr[i]<0){
                //Less than 0 is not enough
                return false;
            }
        }
        return true;
    }
}

             🐬 7. Sum of two numbers

Given an integer array {nums} and an integer target value} target, please find the two} integers} and the target value} target in the array, and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot be repeated in the answer.

You can return answers in any order.

Title Link: Sum of two numbers       

Topic analysis: not too classic topics. I have also explained them in detail in the sum of numbers series. Here is only the practice of hashing for you.

Time complexity O(n): n is the length of nums, mainly the time consumption of the loop

Spatial complexity O(n): n is the length of nums, mainly the overhead of hash

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n=nums.length;
        //key stores the value and value stores the subscript
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<n;i++){
            //eureka
            if(map.containsKey(target-nums[i])){
                //Return subscript
                return new int[]{map.get(target-nums[i]),i};
            }
            //Not found in map
            map.put(nums[i],i);
        }
        //End of traversal still not found
        return new int[0];
    }
}

☀️ 3. Hash summary (Title General link)

Hashing is a classic method of exchanging space for time. It is generally easier for us to timeout when doing questions. Hashing can help us solve this problem. However, basic topics can only be hashed. If advanced topics need to be matched with other methods, such as double pointers, etc. Therefore, we must lay a good foundation for hash and start with simple questions, otherwise we can't think of using hash in the future. In the future, I will also write a collection of advanced hash and exercises of various algorithms. I hope you can collect and support it.

1. There are duplicate elementshttps://leetcode-cn.com/problems/contains-duplicate/
2. There are duplicate elements||https://leetcode-cn.com/problems/contains-duplicate-ii/
3. Effective letter wordshttps://leetcode-cn.com/problems/valid-anagram/
4. Intersection of two arrayshttps://leetcode-cn.com/problems/intersection-of-two-arrays/
5. Happy numberhttps://leetcode-cn.com/problems/happy-number/
6. Ransom letterhttps://leetcode-cn.com/problems/ransom-note/
7. Sum of two numbershttps://leetcode-cn.com/problems/two-sum/
come on.

The old fellow who is helpful, still wants to give a three company. Thank you!!!!        

Surprise at the end of the article:

          

Java learning route summary, brick movers counter attack Java Architects

 

Topics: Algorithm data structure