LeetCode - 3. Hash Table

The order of brushing is from: Code Casual Recording

Alphabetic Words

242. Effective Alphabetic Words

Given two strings s and t, write a function to determine if t is an alphabetic word for s.

Note: If s and t appear the same number of times for each character, then s and T are heterographic words.

Example 1:

input: s = "anagram", t = "nagaram"
output: true

Example 2:

input: s = "rat", t = "car"
output: false
  • 1 <= s.length, t.length <= 5 * 104
  • s and t contain only lowercase letters
public boolean isAnagram(String s, String t) {
    if(s.length() != t.length()) {
        return false;
    }

    int[] sFreq = freq(s);
    int[] tFreq = freq(t);

    for(int i = 0; i < 26; i++) {
        if(sFreq[i] != tFreq[i]) {
            return false;
        }
    }

    return true;
}

public int[] freq(String s) {
    int[] freq = new int[26];  // Stores the occurrence frequency of each letter

    for(int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        freq[ch-'a']++;
    }

    return freq;
}

Redemption Letter

383. Redemption Letter

Give you a ransomNote string and a magazine string to determine if ransomNote can consist of characters in magazines.

  • Each character in magazine can only be used once in ransomNote.
  • ransomNote and magazine are composed of lower case letters

Example 1:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "aab"
Output: true
public boolean canConstruct(String ransomNote, String magazine) {
    // Record the frequency of letters
    int[] rFreq = getFreq(ransomNote), mFreq = getFreq(magazine);

    for(int i = 0; i < 26; i++) {
        if(rFreq[i] > mFreq[i]) {
            return false;
        }
    }
    return true;
}

public int[] getFreq(String s) {
    int[] freq = new int[26];

    for(int i = 0; i < s.length(); i++) {
        freq[s.charAt(i) - 'a']++;
    }

    return freq;
}

Intersection of two arrays

349. Intersection of two arrays

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output:[2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output:[9,4]
  • Each element in the output must be unique.
  • We can ignore the order of the output.

Use HashSet to store the numbers that appear in the array.

public int[] intersection(int[] nums1, int[] nums2) {
    if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
        return new int[0];
    }
    Set<Integer> set1 = new HashSet<>();
    Set<Integer> resSet = new HashSet<>();
    //Traversal Array 1
    for (int i : nums1) {
        set1.add(i);
    }
    //Determine if the element exists in the hash table during traversal of Array 2
    for (int i : nums2) {
        if (set1.contains(i)) {
            resSet.add(i);
        }
    }
    int[] resArr = new int[resSet.size()];
    int index = 0;
    //Convert Result Geometry to Array
    for (int i : resSet) {
        resArr[index++] = i;
    }
    return resArr;
}

350.Intersection of two arrays II

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output:[2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output:[4,9]
  • The number of occurrences of each element in the output should be consistent with the minimum number of occurrences of elements in both arrays.
  • We can ignore the order of the output.

Happy Count

202. Number of pleasures

Write an algorithm to determine if n is a happy number.

"Happy Number" is defined as:

  • For a positive integer, each time the number is replaced with the sum of the numbers at each position.
  • Then repeat the process until this number changes to 1, or it may loop indefinitely but never reach 1.
  • If it can be changed to 1, then this is the number of joys.
// When a number is repeated over and over again, it proves to be in an infinite loop, not a happy number
public boolean isHappy(int n) {
    HashSet<Integer> set = new HashSet<>();  // Save History Operation

    while(n != 1) {
        n = happy(n);
        if(set.contains(n)) {
            return false;
        }
        else {
            set.add(n);
        }
    }

    return true;
}

public int happy(int n) {
    int result = 0;
    while(n != 0) {
        int remainder = n % 10;
        result += remainder * remainder;
        n = n / 10;
    }
    return result;
}

Sum of Two Numbers

1. Sum of Two Numbers

Given an array of integers nums and an integer scalar target, find the two integers in the array that are added to the target target value target and return their array subscripts.

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

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]
public int[] twoSum(int[] nums, int target) {
    HashMap<Integer, Integer> map = new HashMap<>();  // Save Array Index
    int[] result = new int[2];

    for(int i = 0; i < nums.length; i++) {
        // Does a number add up to the current number and be a target before
 		// If so, the index of these two numbers is returned		       
        if(map.containsKey(target - nums[i])) {
            result[0] = map.get(target - nums[i]);
            result[1] = i;
            return result;
        }
        map.put(nums[i], i);
    }
    return null;
}

454.Quaternion Addition II

Give you four integer arrays nums1, nums2, nums3, and nums4. The length of the array is n. Please calculate how many tuples (i, j, k, l) you can have:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

Example 1:

Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
 Explanation:
The two tuples are as follows:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

Example 2:

Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1

Similar to the method in the previous question, after changing from two arrays to four, you need to build a HashMap with two arrays in one unit.

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    if(nums1.length == 0) return 0;

    HashMap<Integer, Integer> map = new HashMap<>();

    // Records the number of times the array elements 1 and 2 are added together
    for(int i = 0; i < nums1.length; i++) {
        for(int j = 0; j < nums2.length; j++) {
            map.put(nums1[i]+nums2[j], map.getOrDefault(nums1[i]+nums2[j], 0) + 1);
        }
    }

    int count = 0;
    for(int i = 0; i < nums3.length; i++) {
        for(int j = 0; j < nums4.length; j++) {
            count += map.getOrDefault(-nums3[i]-nums4[j], 0);
        }
    }

    return count;
}

Sum of Three Numbers

15.Sum of Three Numbers

Give you a n array of nums containing n integers, and determine if there are three elements a, b, c in nums so that a + b + c = 0? Please find all triples with sum 0 and no repetition.

Note: The answer cannot contain duplicate tuples.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output:[[-1,-1,2],[-1,0,1]]

Example 2:

Input: nums = [0]
Output:[]

First, sort the arrays, and move the big loop one space at a time from left to right. In each big loop, find the triple through the double pointer. Note the two de-weighting codes.

public List<List<Integer>> threeSum(int[] nums) {
    if(nums.length < 3) return new ArrayList();

    Arrays.sort(nums);  // sort
    List<List<Integer>> res = new ArrayList<>();

    for(int i = 0; i < nums.length - 2; i++) {
        // Duplicate removal
        if(i >= 1 && nums[i] == nums[i-1]) {
            continue;
        }

        int left = i + 1;
        int right = nums.length - 1;

        while(left < right) {
            if(nums[i] + nums[left] + nums[right] == 0) {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(nums[i]);
                list.add(nums[left]);
                list.add(nums[right]);
                res.add(list);
				
                // Duplicate removal
                while(left < right && nums[left] == nums[++left]) { }
            }
            else if(nums[i] + nums[left] + nums[right] < 0) {
                left++;
            }
            else {
                right--;
            }
        }
    }

    return res;
}

18.Sum of Quarters

Give you an array of n integers, nums, and a target value. Please find and return the four tuples [nums[a], nums[b], nums[c], nums[d], which satisfy all the following conditions and do not repeat (two quaternions are considered duplicates if they correspond to one another):

  • 0 <= a, b, c, d < n
  • a, b, c and d are different from each other
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You can return the answers in any order.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
 Output:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
 Output:[[2,2,2,2]]

Similar to the previous question, you need a double cycle + double pointer, and the extra cycle needs to be weighted.

public List<List<Integer>> fourSum(int[] nums, int target) {
    if(nums.length < 4) return new ArrayList();

    ArrayList<List<Integer>> res = new ArrayList<>();
    Arrays.sort(nums);

    for(int i = 0; i < nums.length - 3; i++) {
        if(i > 0 && nums[i] == nums[i-1]) continue;  // Duplicate removal
        for(int j = i + 1; j < nums.length - 2; j++) {
            if(j > i + 1 && nums[j] == nums[j-1]) continue;  // Duplicate removal  
            int left = j + 1, right = nums.length - 1;

            while(left < right) {
                if(nums[i] + nums[j] + nums[left] + nums[right] == target) {
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    res.add(list);

                    while(left < right && nums[left] == nums[++left]) {}  // Duplicate removal
                }
                else if(nums[i] + nums[j] + nums[left] + nums[right] < target) {
                    left++;
                }
                else {
                    right--;
                }
            }

        }
    }

    return res;
}

Tags: leetcode

Posted on Sat, 27 Nov 2021 12:25:20 -0500 by kumar_ldh