1. 程式人生 > >leetcode簡單(161-180)python

leetcode簡單(161-180)python

690. Employee Importance(e-161)

You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct

.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

class Employee(object):
    def __init__(self, id, importance, subordinates):
        # It's the unique id of each node.
        # unique id of this employee
        self.id = id
        # the importance value of this employee
        self.importance = importance
        # the id of direct subordinates
        self.subordinates = subordinates
 
 
class Solution(object):
 
    def getImportance(self, employees, id):
        """
        :type employees: Employee
        :type id: int
        :rtype: int
        """
        # Time: O(n)
        # Space: O(n)
        emps = {employee.id: employee for employee in employees}
        def dfs(id):
            subordinates_importance = sum([dfs(sub_id) for sub_id in emps[id].subordinates])
            return subordinates_importance + emps[id].importance
        return dfs(id)
 

693. Binary Number with Alternating Bits(e-162)

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        flag=n%2
        n=n//2
        while n>0:
            if n%2==flag:
                return False
            flag=n%2
            n=n//2
        return True

695. Max Area of Island(e-163)

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

class Solution(object):
       def maxAreaOfIsland(self, grid):
        m, n = len(grid), len(grid[0])
 
        def dfs(i, j):
            if 0 <= i < m and 0 <= j < n and grid[i][j]:
                grid[i][j] = 0
                return 1 + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1)
            return 0
 
        areas = [dfs(i, j) for i in range(m) for j in range(n) if grid[i][j]]
        return max(areas) if areas else 0

696. Count Binary Substrings(e-164)

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

class Solution(object):
    def countBinarySubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        group=[1]
        for i in range(1,len(s)):
            if s[i-1]!=s[i]:
                group.append(1)
            else:
                group[-1]+=1
            
        ans=0
        for i in range(1, len(group)):
            ans+=min(group[i-1], group[i])
        return ans
        

697. Degree of an Array(e-165)

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums

class Solution(object):
    def findShortestSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #定義字典元素以及對應的位置資訊,count記錄每個元素出現的次數
        left, right, count = {}, {}, {}
        for i, num in enumerate(nums):
            #如果元素num第一次出現,則存入left中
            if num not in left:
                left[num] = i
            #將出現的元素及對應的位置資訊存入right中
            right[num] = i
            #每個元素出現一次,則count對位num位置的數值 +1
            count[num] = count.get(num, 0) + 1
        
        ans = len(nums)
        degree = max(count.values())
        for num in count:
            if count[num]==degree:
                ans = min(ans, right[num]-left[num]+1)
        return ans

700. Search in a Binary Search Tree(e-166)---------------

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

703. Kth Largest Element in a Stream(e-167)--------------

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

704. Binary Search(e-168)

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search targetin nums. If target exists, then return its index, otherwise return -1.

class Solution:
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                left = mid + 1
            else:
                right = mid - 1
        return -1

705. Design HashSet(e-169)-------

Design a HashSet without using any built-in hash table libraries.

To be specific, your design should include these two functions:

  • add(value): Insert a value into the HashSet. 
  • contains(value) : Return whether the value exists in the HashSet or not.
  • remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.

706. Design HashMap(e-170)-------------

Design a HashMap without using any built-in hash table libraries.

To be specific, your design should include these two functions:

  • put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
  • get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.