Leetcode- hash table

242. Effective ectopic letter word  https://leetcode-cn.com/problems/valid-anagram/

Given two strings s and t, t write a function to determine whether the ectopic letters of the word s. I.e., the same letters but in a different order.

Example 1:

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

Example 2:

Input: s = "rat", t = "car"
Output: false
Description:
You can assume string contains only lowercase letters.

Advanced:
If the input string contains unicode characters how to do? Can you adjust your solution to deal with this situation?

solution:

S and t are sorted for Comparative sorted string. O (NlogN)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

  

Counts each letter of the string with hashmap. O (N)

Solution has a class: 
    def Are isAnagram (self, s is: do something like str, t is a: do something like str), -> for the bool: 
        
        def Are countaph (s is),: 
            aphs = of dict is (), 
            pics char-in, s is: 
                aphs, [char], = aphsget (char, have 0), +, fan_hui have 0 # zhao_bu_dao on the Key jiu 1 
            the Return aphs 
        
        aphs = countaph (s is), 
        apht = countaph (t is a), 
        
        IF at the aphs == apht: 
            the Return When set to True 
        the Return in False

   

1. The sum of two numbers  https://leetcode-cn.com/problems/two-sum/

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

solution:

Violence to solve, through all possible first number, second number of nested traversal. O (N 2 ), it may time out

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if nums is None or len(nums) <= 1 :
            return []
        n = len(nums)
        for i in range(n):
            for j in range(i+1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

  

Hash table, y = target - x, enumerate x, query y. You can traverse over the same time to keep the hash table, and then enumerate the query x y.

It can also be saved while traversing the hash table when the query immediately. O (N).

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if nums is None or len(nums) <= 1 :
            return []
        n = len(nums)
        visited = dict()
        for i in range(n):
            visited[nums[i]] = i
        
        for i in range(n):
            y = target - nums[i]
            if y in visited and visited.get(y) != i:  # y在哈希表中且不重复利用同样的元素
                return [i, visited.get(y)]
        return []

  

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if nums is None or len(nums) <= 1 :
            return []
        n = len(nums)
        visited = dict()
        for i in range(n):
            y = target - nums[i]
            if y in visited and visited.get(y) != i:
                return [visited.get(y), i]  # 这时候就是索引i在后了
            visited[nums[i]] = i
        return []

  

15. three number Noriyuki sum  https://leetcode-cn.com/problems/3sum/

Given an array nums n comprises integers, it determines whether there are three elements a, b, c nums such that a + b + c = 0? Satisfying the condition will not be repeated to identify all of the triples.

Note: The answer can not contain duplicate triples.

solution:

Violence to solve, three nested, O (N 3 ), do not write.

x + y + z = target, enumeration x, y, again hash table query target - x - y. O (N 2 )

The following code is stored on the table into the hash method, explained further:

Solution class: 
    DEF threeSum (Self, the nums: List [int]) -> List [List [int]]: 
        IF len (the nums) <. 3: 
            return [] 
        
        nums.sort () # what sort first, to facilitate the determination heavy 
        res SET = () 
        
        for I, X in the enumerate (the nums [: -2]): 
            IF I> = == X. 1 and the nums [-I. 1]: 
                Continue 
            # determined for each x, y and find z, degradation and the number of questions in two 
            d = {} 
            for y in the nums [I +. 1:]: 
                IF not in y d: 
                    d [-XY] = d. 1 # If y is not in the matched pattern of current y z ( i.e. -XY) into the d memory, so if traversed in a y d, then the corresponding z (i.e. -XY) d is in constant, but nums [i + 1:] elements and less than y 
                the else : 
                    res.add ((X, -XY, Y)) 
        return List (Map (List, RES))

  

sort & find, first sort O (NlogN), as the first element of the enumeration x, y and z find the rest of the array, i.e. to both sides sandwiching. O (N 2 ), no additional space.

Solution class: 
    DEF threeSum (Self, the nums: List [int]) -> List [List [int]]: 
        IF len (the nums) <. 3: 
            return [] 
        RES = [] 
        nums.sort () 
        n-len = (the nums ) 
        for I in Range (-n-2): 
            IF I> 0 and the nums [I] == the nums [-I. 1]: # de-emphasis, if the same number of first, skipped 
                Continue 
            L, R & lt. 1 = I + , n--. 1 
            the while L <R & lt: 
                S = the nums [I] + the nums [L] + the nums [R & lt] 
                IF S <0: 
                    L + =. 1 
                elif S> 0: 
                    R & lt - =. 1 
                the else: 
                    res.append((nums[i], nums[l], nums[r]))  # 记录解
                    # de-emphasis, if second, the same as the third number, skip 
                    the while L <R & lt and the nums [L] == the nums [L +. 1]: 
                        L = +. 1 
                    the while L <R & lt and the nums [R & lt] == the nums [-R & lt. 1]: 
                        R & lt -. 1 = 
                    # of possible solutions continue to find 
                    L =. 1 + 
                    R & lt - =. 1 
        return RES

  

18. four number Noriyuki sum  https://leetcode-cn.com/problems/4sum/

Given a n array of integers and a target nums target, if there are four elements a, b, c, and d nums determined such that a + b + c + d is equal to the value of the target? Identify all satisfy the conditions of the quad and do not repeat.

note:

The answer can not contain duplicate quad.

solution:

And three and the number of basically the same idea, a fixed number of two, to find the two numbers.

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        
        nums.sort()  # 先排序一下,便于判重
        res = set()
        n = len(nums)
        
        for i in range(n-3):
            if i >0 and nums[i] == nums[i-1]:
                continue
                
            for j in range(i+1, n-2):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                d = {}
                for z in nums[j+1:]:
                    if not z in d:
                        d[target-nums[i]-nums[j]-z] = 1
                    else:
                        res.add((nums[i], nums[j], target-nums[i]-nums[j]-z, z))

        return list(map(list, res))

  

Since the outer layer has two nested, consider doing it then be sentenced to heavy pruning

Solution class: 
    DEF fourSum (Self, the nums: List [int], target: int) -> List [List [int]]: 
        IF len (the nums) <. 4: 
            return [] 
        RES = [] 
        nums.sort () 
        n- len = (the nums) 
        for I in Range (. 3-n-): 
            IF I> 0 and the nums [I] == the nums [-I. 1]: # de-emphasis, if the same number of first, skipped 
                Continue 
            # pruning if the current x and the number of the remaining three and greater than the minimum or the maximum of the number of target and less than target three, skip 
            if nums [i] + sum ( nums [i + 1: i + 4])> target the nums or [I] + SUM (the nums [-3:]) <target: 
                Continue 
            
            for J in Range (I +. 1, n-2-): 
                IF J> I +. 1 and the nums [J] == the nums [J- 1]: # de-duplication, the same if the first number, skip 
                    continue
                the nums IF [I] + the nums [J] + SUM (the nums [+ J. 1: J +. 3])> target: 
                    Continue 
                IF the nums [I] + the nums [J] + SUM (the nums [-2:]) <target : 
                    Continue 
                    
                L, R & lt J + =. 1,. 1-n- 
                the while L <R & lt: 
                    S = target-the nums [I] -nums [J] -nums [L] -nums [R & lt] 
                    IF S <0: number of about # big and 
                        R & lt - =. 1 
                    elif S> 0: 
                        L =. 1 + 
                    the else: 
                        res.append ((the nums [I], the nums [J], the nums [L], the nums [R & lt])) # recording solution 
                        # deduplication If the second, third same number, skip 
                        while l <r and nums [l ] == nums [l + 1]:
                            =. 1 + L 
                        the while L <R & lt and the nums [R & lt] == the nums [-R & lt. 1]: 
                            R & lt -. 1 = 
                        # of possible solutions continue to find 
                        L =. 1 + 
                        R & lt - =. 1 
        return RES

  

49. The letter ectopic grouping words  https://leetcode-cn.com/problems/group-anagrams/

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"]
]
说明:

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

solution:

# 242 extensions, note dict is unhashable can not be used as another key dictionary, so here it is to determine whether to use the word ectopic sorted. O (NKlogK)

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        if len(strs) <= 1:
            return [strs]
        words = dict()
        for s in strs:
            key = tuple(sorted(s))
            if not key in words:
                words[key] = [s]
            else:
                words[key].append(s)
        return list(words.values())

  

Counting the classified lowercase letters, avoid using dictionaries

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        if len(strs) <= 1:
            return [strs]
        words = dict()
        for s in strs:
            count = [0]*26
            for c in s:
                count[ord(c) - ord('a')] += 1  # 避免了用字典
            key = tuple(count)
            if not key in words:
                words[key] = [s]
            else:
                words[key].append(s)
        return list(words.values())

  

 

Guess you like

Origin www.cnblogs.com/chaojunwang-ml/p/11353656.html