leetcode(121-140)简单题python

532. K-diff Pairs in an Array(121)

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k >0:
            return len(set(nums) & (set(n+k for n in nums)))
        elif k==0:
            return sum(v>1 for v in collections.Counter(nums).values())
        else:
            return 0

538. Convert BST to Greater Tree(e-122)------------

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

541. Reverse String II(e-123)

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        if not s:
            return s
        ans=''
        for i in range(0, len(s), 2*k):
            ans+=s[i:i+k][::-1]
            ans+=s[i+k:i+2*k]
        return ans
    
    

    

543. Diameter of Binary Tree(e-124)-----------

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

551. Student Attendance Record I(e-125)

 

You are given a string representing an attendance record for a student. The record only contains the following three characters:

 

  1. 'A' : Absent.
  2. 'L' : Late.
  3. 'P' : Present.

 

A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

class Solution(object):
    def checkRecord(self, s):
        """
        :type s: str
        :rtype: bool
        """
        a=collections.Counter(s)
        b=s.find("LLL")
        return a['A']<=1 and b==-1
        
        

557. Reverse Words in a String III(e-126)

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        s=s.split()
        for i, word in enumerate(s):
            s[i]=word[::-1]
        return " ".join(s)

558. Quad Tree Intersection(e-127)

A quadtree is a tree data in which each internal node has exactly four children: topLefttopRightbottomLeft and bottomRight. Quad trees are often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions.

We want to store True/False information in our quad tree. The quad tree is used to represent a N * N boolean grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same. Each node has another two boolean attributes : isLeaf and valisLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.

For example, below are two quad trees A and B:

559. Maximum Depth of N-ary Tree(e-128)

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

 

 

We should return its max depth, which is 3.

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

561. Array Partition I(e-129)

 

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(c for i, c in enumerate(sorted(nums))if i %2==0)

563. Binary Tree Tilt(e-130)---------

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

566. Reshape the Matrix(e-131)

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

class Solution(object):
    def matrixReshape(self, nums, r, c):
        m, n = len(nums), len(nums and nums[0])
        if r * c != m * n or r < 0 or c < 0:
            return nums
        return [[nums[(i*c+j)/n][(i*c+j)%n] for j in xrange(c)] for i in xrange(r)]
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """

572. Subtree of Another Tree(e-132)---------------------

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

575. Distribute Candies(e-133)

 

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

class Solution(object):
    def distributeCandies(self, candies):
        """
        :type candies: List[int]
        :rtype: int
        """
        return min(len(candies)/2, len(set(candies)))

581. Shortest Unsorted Continuous Subarray(e-134)

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        start=-1
        end=-1
        so=sorted(nums)
        for i in range(0,len(nums)):
            if so[i] !=nums[i]:
                if start==-1:
                    start=i
                end=i
        return end-start+1 if end!=start else 0
                
        

589. N-ary Tree Preorder Traversal(e-135)-----------

Given an n-ary tree, return the preorder traversal of its nodes' values.

 

For example, given a 3-ary tree:

 

Return its preorder traversal as: [1,3,5,6,2,4].

590. N-ary Tree Postorder Traversal(e-136)---------

Given an n-ary tree, return the postorder traversal of its nodes' values.

 

For example, given a 3-ary tree:

 

Return its postorder traversal as: [5,6,3,2,4,1].

594. Longest Harmonious Subsequence(e-137)

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

class Solution(object):
    def findLHS(self, nums):
        counts=collections.Counter(nums)
        return max([counts[i]+counts[i+1] for i in counts if counts[i+1]] or [0])

598. Range Addition II(e-138)

Given an m * n matrix M initialized with all 0's and several update operations.

Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.

You need to count and return the number of maximum integers in the matrix after performing all the operations.

class Solution(object):
    def maxCount(self, m, n, ops):
        """
        :type m: int
        :type n: int
        :type ops: List[List[int]]
        :rtype: int
        """
        return reduce(operator.mul, map(min, zip(*ops + [[m,n]])))
            

599. Minimum Index Sum of Two Lists(e-139)

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

class Solution(object):
    def findRestaurant(self, list1, list2):
        """
        :type list1: List[str]
        :type list2: List[str]
        :rtype: List[str]
        """
        dic1 = {v:i for i,v in enumerate(list1)}
        best,ans = 1e9,[]
        for i,v in enumerate(list2):
            if v in dic1:
                if i+dic1[v] < best:
                    best = i+dic1[v]
                    ans = [v]
                elif i+dic1[v] == best:
                    ans.append(v)
        return ans

605. Can Place Flowers(e-140)

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        for i in range(len(flowerbed)):
            if flowerbed[i] == 0 and (i==0 or flowerbed[i-1]==0) and (i==len(flowerbed)-1 or flowerbed[i+1] == 0):
                flowerbed[i] =1
                n-=1
        return n<=0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值