LeetCode lookup table Theme 5: flexibility to choose key: 4Sum II

LeetCode lookup table Theme 5: flexibility to choose key: 4Sum II

Example 1: LeetCode 454 Title: four numbers together II

Portal: English Website: 454. 4Sum II , Chinese website: 454. four numbers together II .

Given an array of integers containing the list of four A, B, C, D, calculate how many tuples (i, j, k, l)so A[i] + B[j] + C[k] + D[l] = 0.

In order to simplify the problem, all of the A, B, C, D have the same length N, and 0 ≤ N ≤ 500. All integer in the range of -228 to 228-- between 1, the end result will not be exceeded.

E.g:

输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

输出:
2

解释:
两个元组如下:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Analysis: In fact, as long as the clear thinking, is a very simple question. The A, B, C, D into two groups to find and C, D and opposite to the sum of the same number of combinations A, B sum, to use this data structure HashMap. The effects of several combinations of multiplication counting principle. There are coding skills, they must be.

Python code 1: Remember that on the basis of understanding

class Solution:
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """

        map1 = self.get_map(A, B)
        map2 = self.get_map(C, D)
        res = 0

        for key1 in map1:
            if -key1 in map2:
                res += map1[key1] * map2[-key1]
        return res

    def get_map(self, tuple1, tuple2):
        map = dict()
        for num1 in tuple1:
            for num2 in tuple2:
                map[num1 + num2] = (map.setdefault(num1 + num2, 0) + 1)
        return map

Python code: hereinafter this wording save a map, but at the time of calculation, the multiplication can not be used, only with the addition, to this difference

class Solution:
    def fourSumCount(self, A, B, C, D):
        """
        :type A: List[int]
        :type B: List[int]
        :type C: List[int]
        :type D: List[int]
        :rtype: int
        """

        map = dict()
        for num3 in C:
            for num4 in D:
                map[num3 + num4] = (map.setdefault(num3 + num4, 0) + 1)

        res = 0

        for num1 in A:
            for num2 in B:
                s = num1 + num2
                if -s in map:
                    res += map[-s]
        return res

Java code: ditto

/* 分治,把4个list,拆成两两组合,降低complexity
* Time complexity: O(n^2), space complexity: O(n^2) */
class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> hm = new HashMap<>();
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                hm.put(A[i] + B[j], hm.getOrDefault(A[i] + B[j], 0) + 1);
            }
        }
        int res = 0;
        for (int i = 0; i < C.length; i++) {
            for (int j = 0; j < D.length; j++) {
               res += hm.getOrDefault((C[i] + D[j]) * -1, 0);
            }
        }
        return res;
    }
}

Exercise: examples: LeetCode 49 questions: ectopic letter word grouping

Portal: English Website: 49. Group the Anagrams , Chinese website: 49. ectopic letter word grouping .

Given a string array, ectopic word letters together. Ectopic word letters refer to the same letters, but arranged in different strings.

Example:

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

Description:

  • All inputs are lowercase letters.
  • The order of the answers that were not considered.

1 idea: can be completed with a map, key is the character after the sort.

414598-7ccbf0afff350829.png
image

Python code:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        map = dict()

        if len(strs) == 0:
            return []

        for s in strs:
            key = ''.join(sorted(list(s)))
            if key not in map:
                map[key] = [s]
            else:
                map[key].append(s)

        return list(map.values())

In the official title to see off his answer, you can take a direct tuple hash table as key.

Python code:

class Solution(object):
    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for s in strs:
            ans[tuple(sorted(s))].append(s)
        return ans.values()

It has not changed the nature of this solution below, but the key is not the same.

414598-84b9e5354d97ad87.png
image

Notes that only 26 letters of the alphabet, so if you do not sort it, direct statistics letter frequencies are possible, the letter frequencies as the key array becomes tuple hash table.

Python code:

class Solution:
    def groupAnagrams(strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
        return ans.values()

Ideas 2: Profiled body can do to encoding, encoding as it should be in a group inside. In many cases, the function hash table can be replaced with an array. The following two editions of the code time complexity is too high, we have a look at this idea on it.

Python code:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 26 个质数
        primes = [2, 3, 5, 7, 11,
                  13, 17, 19, 23, 29,
                  31, 37, 41, 43, 47,
                  53, 59, 61, 67, 71,
                  73, 79, 83, 89, 97,
                  101]

        # hash_arr 中存放的是与 res 对应的 hash 值
        hash_arr = []
        res = []

        for s in strs:
            hash_val = 1
            for alpha in s:
                hash_val *= primes[ord(alpha) - ord('a')]
            index = 0
            while index < len(hash_arr):
                if hash_arr[index] == hash_val:
                    res[index].append(s)
                    break
                index += 1
            if index == len(hash_arr):
                hash_arr.append(hash_val)
                res.append([s])
        return res


if __name__ == '__main__':
    strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
    solution = Solution()
    result = solution.groupAnagrams(strs)
    print(result)

Python code:

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        # 26 个质数
        primes = [2, 3, 5, 7, 11,
                  13, 17, 19, 23, 29,
                  31, 37, 41, 43, 47,
                  53, 59, 61, 67, 71,
                  73, 79, 83, 89, 97,
                  101]

        # hash_arr 中存放的是与 res 对应的 hash 值
        hash_arr = []
        res = []

        for s in strs:
            hash_val = 1
            for alpha in s:
                hash_val *= primes[ord(alpha) - ord('a')]

            found = False
            index = 0
            while index < len(hash_arr):
                if hash_arr[index] == hash_val:
                    res[index].append(s)
                    found = True
                    break
                index += 1
            # 如果没有找到,就加在后面,hash_arr 和 res 是同步的
            if not found:
                hash_arr.append(hash_val)
                res.append([s])
        return res

(End of this section)

Guess you like

Origin blog.csdn.net/weixin_34258078/article/details/90885261