Leetcode--Hash table concept summary and classic topic analysis

table of Contents

Topic 1: Conjugation phrase

Topic 2: The sum of two numbers

Topic 3: Number pairs and sum

Topic Four: Effective Letter Variant Words

Topic 5: How many numbers are equivalent to the current number

Topic 6: Rabbits in the forest

Topic 7: Sort according to the frequency of characters


Hash table

    Mainly use the key-value pair feature of hashmap to process data.

A piece of commonly used code summarized by the individual:

When the value corresponding to a key in the map needs to be changed by +1, first take out the value corresponding to the key, and then add 1 to the value and put it back into the map.

if(map.containsKey(key1)){
    int tempcount = map.get(keys)+1;
    map.put(key1,tempcount);
}

 

Topic 1: Conjugation phrase

(Subject link: https://leetcode-cn.com/problems/group-anagrams-lcci )

Write a method to sort an array of strings and group all anagrams together. An anagram is a character string with the same letters but a different arrangement.

Note: This question is slightly modified from the original question

Example:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
说明:

All entries are in lowercase letters.
The order in which the answers are output is not considered.

Method: Use the hashmap storage structure for data storage, where the string stored in the key contains the same letters and the same order, and the value storage contains the same letters but also the order in a different order.

Java source code

import java.util.*;

public class hashword {
    public static void main(String[] args) {
        String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> strs2 = new ArrayList<List<String>>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (int i = 0; i <strs.length ; i++) {
            char[] arr = strs[i].toCharArray();
            Arrays.sort(arr);
            String arrstr = new String(arr);
            if(!map.containsKey(arrstr)){
                List<String> templiststring = new ArrayList<>();
                templiststring.add(strs[i]);
                map.put(arrstr,templiststring);
            }
            else{
                map.get(arrstr).add(strs[i]);
            }
        }
        for(String key :map.keySet()){
            strs2.add(map.get(key));
        }
        System.out.println("value: "+strs2);
    }
}

The most important steps:

    Remember to convert the string to be processed into a character array, and then sort the character array.

[Note]: Summary of ideas: the new hash structure HashMap<String, List<String>>(); Note that this is a thinking I did not have before, that is, the key and value in the map are traditionally corresponding to each other.

But we locate the data structure form of value as list<String>, which essentially realizes one-to-many storage. This kind of hash thinking pays attention to the summary

[Note]: Syntax summary: To change the character array into a string, we use String arrstr = new String(arr);

                                    To turn a string into a character array, we use char[] arr = str.toCharArray();

[Note]: Syntax summary: Arrays.sort(arr) can realize automatic sorting of arrays

Topic 2: The sum of two numbers

(Subject link: https://leetcode-cn.com/problems/two-sum )

Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.

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

You can return the answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Method 1: Direct for loop, which is relatively simple, we will not show the code

Method 2: Here we mainly explain the method of using hash to solve the problem

The official idea: use a hash table to store the value of the array and the index of the array: the value of the array corresponds to the key of the hashtable, and the index of the array corresponds to the value of the hashtable.

    Through a for loop, determine whether target-nums[i] is in the hashtable. If it is, it is found and the result is returned. If it is not, then num[i], and i are stored in the hashtable.

Java source code

import java.util.HashMap;
import java.util.Map;

public class twocount_sum {
    public static void main(String[] args) {
        int[] nums = new int[]{2,6,7,15};
        int target = 9;
        int result[] = new int[2];
        Map<Integer,Integer> hashtable = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++) {
            if(hashtable.containsKey(target - nums[i])){
                result[0] = i ;
                result[1] = hashtable.get(target-nums[i]);
            }else{
                hashtable.put(nums[i], i);
            }

        }
        for (int i = 0; i < 2; i++) {
            System.out.println(result[i]);
        }
    }
}

 The code written for the second time:

import java.util.*;


public class Solution {
    /**
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
        // write code here
        int[] res = new int[2];
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i =0;i<numbers.length;i++){
            map.put(numbers[i],i+1);
        }
        for(int i =0;i<numbers.length;i++){
            
            if(map.containsKey(target - numbers[i])){
                if( (i+1) != map.get(target - numbers[i])){
                    res[0] = i+1;
                res[1] = map.get(target-numbers[i]);
                break;
                }
                
            }
        }
        return res;
    }
}

Topic 3: Number pairs and sum

(Subject link: https://leetcode-cn.com/problems/pairs-with-sum-lcci/ )

Design an algorithm to find all integer pairs in the array whose sum of two numbers is a specified value. A number can only belong to one number pair.

Example 1:

Input: nums = [5,6,5], target = 11
Output: [[5,6]]
Example 2:

Input: nums = [5,6,5,6], target = 11
Output: [[5,6],[5,6]]

Idea: Use hashtable to store elements in an array

Official: follow up on the official concise code

Java source code:

class Solution {
    public List<List<Integer>> pairSums(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Map<Integer,Integer> map1 = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if(map1.containsKey(nums[i])){
                int tempcount = map1.get(nums[i]) +1;
                map1.put(nums[i] , tempcount);
            }else{
                map1.put(nums[i],1);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if(map1.containsKey(target- nums[i]) ){
                if(map1.get(target - nums[i]) >0){
                    
                    //System.out.println("first: "+nums[i]+" second: "+(int)(target- nums[i]));
                    int tempcount2 = map1.get(target - nums[i])-1;
                    map1.put( target - nums[i],tempcount2);
                    if(map1.get(nums[i]) >0){
                        List<Integer> tempres = new ArrayList<Integer>();
                    tempres.add(nums[i]);
                    tempres.add((int)(target- nums[i]));
                    res.add(tempres);
                    }
                    int tempcount3 = map1.get(nums[i])-1;
                    map1.put(nums[i],tempcount3);
                }
            }

        }
        return res;
    }
}

Topic Four: Effective Letter Variant Words

(Subject link: https://leetcode-cn.com/problems/valid-anagram/ )

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

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false

Method 1: Turn the string into a character array, sort the character array, and the sorted character array becomes a string, and judge whether the two strings are equal .

Java source code:

class Solution {
    public boolean isAnagram(String s, String t) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        char[] chart = t.toCharArray();
        Arrays.sort(chart);
        if(Arrays.toString(chars).equals(Arrays.toString(chart))){
            return true;
        }else {
            return false;
        }
    }
}

Method 2: Use an array to determine the number of occurrences of each character.

         Official method: traverse the first string, if a certain character appears, then the number of occurrences will increase by 1, traverse the second string, if a certain character appears, then the counted number of times will be reduced by 1.

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] table = new int[26];
        for (int i = 0; i < s.length(); i++) {
            table[s.charAt(i)-'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            table[t.charAt(i)-'a']--;
        }
        for (int i = 0; i < 26; i++) {
            if(table[i]!=0){
                return false;
            }
        }
        return true;
    }
}

 The second code

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        int slength = s.length();
        int tlength = t.length();
        if(slength != tlength){
            return false;
        }else{
            for(int i =0;i<slength;i++){
                if(map.containsKey(s.charAt(i))){
                    int tempcount = map.get(s.charAt(i))+1;
                    map.put(s.charAt(i),tempcount);
                }else{
                    map.put(s.charAt(i),1);
                }
            }
           for(int j =0;j<tlength;j++){
               if(map.containsKey(t.charAt(j))){
                   int tempcount2 = map.get(t.charAt(j))-1;
                   map.put(t.charAt(j),tempcount2);
               }else{
                   return false;
               }
           }
           for(char key:map.keySet()){
               if(map.get(key)!=0){
                   return false;
               }
           }
           return true;
        }
    }
}

Topic 5: How many numbers are equivalent to the current number

(Subject link: https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/ )

Give you an array nums, for each element nums[i], please count the number of all numbers smaller than it in the array.

In other words, for each nums[i] you must calculate the number of valid j, where j satisfies j != i and nums[j] <nums[i].

The answer is returned as an array.

Example 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there are four numbers smaller than it: (1, 2 , 2 and 3). 
For nums[1]=1, there is no smaller number than it.
For nums[2]=2 there is a smaller number: (1). 
For nums[3]=2 there is a smaller number: (1). 
For nums[4]=3 there are three smaller numbers: (1, 2 and 2).

Idea: Directly double the for loop, solve it with violence

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int[] res = new int[nums.length];
        for(int i =0;i<res.length;i++){
            res[i]=0;
        }
        for(int i =0; i< nums.length;i++){
            for(int j =0; j<nums.length;j++){
                if(nums[i]>nums[j]){
                    res[i]++;
                }
            }
        }
        return res;
    }
}

Topic 6: Rabbits in the forest

Link: https://leetcode-cn.com/problems/rabbits-in-forest

In the forest, every rabbit has a color. Some of these rabbits (maybe all) tell you how many other rabbits have the same color as yourself. We put these answers in the answers array.

Return the minimum number of rabbits in the forest.

Example:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
Two rabbits who answered "1" may have the same color, set to red.
The rabbits who answered "2" afterwards will not be red, otherwise their answers will contradict each other.
Let the rabbit that answered "2" be blue.
In addition, there should be two other blue rabbits in the forest whose answers are not included in the array.
So the minimum number of rabbits in the forest is 5: 3 answered and 2 unanswered.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0

Idea: Mainly find the key to logic:

Assuming that the number of rabbits answering k is v = count[k], through the above analysis, we can know that there are at least a rabbits, where a is the minimum k + 1 multiple that satisfies a >= count[k].

class Solution {
    public int numRabbits(int[] answers) {
        int res = 0;
        Map<Integer,Integer> hashtable = new HashMap<Integer,Integer>();
        for (int i = 0; i <answers.length ; i++) {
            if(hashtable.containsKey(answers[i])){
                int temp = hashtable.get(answers[i])+1;
                hashtable.put(answers[i],temp);
            }else{
                hashtable.put(answers[i],1);
            }
        }
        for (int key : hashtable.keySet()){
            for(int i =1; ;i++){
                int curr = (key+1)*i;
                if(curr >= hashtable.get(key)){
                    res = res + curr;
                    break;
                }
            }
        }
        return res;
    }
}

Topic 7: Sort according to the frequency of characters

(Link: https://leetcode-cn.com/problems/sort-characters-by-frequency/ )

Given a string, please sort the characters in the string in descending order of frequency of appearance.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice, and both'r' and't' only appear once.
Therefore,'e' must appear before'r' and't'. In addition, "eetr" is also a valid answer.

Idea: Use a hash table to store each character and their frequency, sort according to the value of the hash table, and output

class Solution {
    public String frequencySort(String s) {
        Map<Character,Integer> hashtable = new HashMap<Character,Integer>();
        for (int i = 0; i < s.length(); i++) {
            char curr = s.charAt(i);
            if(hashtable.containsKey(curr)){
                int currcount=hashtable.get(curr)+1;
                hashtable.put(curr,currcount);
            }else{
                hashtable.put(curr,1);
            }
        }
        int[] value = new int[hashtable.size()];
        int i = 0;
        char[] key = new char[hashtable.size()];
        int j =0;
        for(Character keyi: hashtable.keySet()){
            value[i++] = hashtable.get(keyi);
            key[j++] = keyi;
        }
        //System.out.println(Arrays.toString(key));
        //System.out.println(Arrays.toString(value));
        for (int k = 0; k < value.length-1; k++) {
            for (int l = 0; l < value.length-k-1; l++) {
                if(value[l] < value[l+1]){
                    int temp = value[l];
                    value[l] = value[l+1];
                    value[l+1] = temp;
                    char temp2 = key[l];
                    key[l] = key[l+1];
                    key[l+1] = temp2;
                }
            }
        }
        String res="";
        for (int k = 0; k < key.length; k++) {
            for (int l = 0; l < value[k]; l++) {
                res += key[k];
            }
        }
        return res;
    }
}

 

Guess you like

Origin blog.csdn.net/yezonghui/article/details/112102687