Python basic grammar and data agency contact--day02

Maximum perimeter of a triangle

Topic link: 976. Maximum perimeter of a triangle

image-20220419103312743

The initial idea of ​​seeing this question should be to triple traverse all combinations, and then find the maximum perimeter that meets the conditions, but this kind of look at the data range knows that it will definitely time out

So the method used is:排序+贪心

Sort the array first (sort), then traverse from back to front (greedy)

What is greed? If you want to find the maximum perimeter, then I will find the maximum side that each side can take. If they can form a triangle, then the triangle formed by him must be the largest.

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月19日
描述: https://leetcode-cn.com/problems/largest-perimeter-triangle/
"""
from typing import List


class Solution:
    def largestPerimeter(self, nums: List[int]) -> int:
        nums.sort()
        for i in range(len(nums) - 1, 1, -1):
            if nums[i] < nums[i - 1] + nums[i - 2]:
                return nums[i] + nums[i - 1] + nums[i - 2]
        return 0

Find the closest point with the same X or Y coordinate

Topic link: 1779. Find the nearest point with the same X or Y coordinate

image-20220419103714309

This question originally wanted to be greedy after sorting, but when sorting, you need to consider both x and y, which is not easy to do, or traverse all directly, and only need to traverse once O(n), and the speed is not bad

So just traverse all of them once, and then maintain a minimum and minimum subscripts. If the effective distance is found to be smaller than the current minimum distance, update the subscripts of the minimum and minimum values ​​at the same time.

# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月19日
描述: https://leetcode-cn.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/
"""
from typing import List


class Solution:
    def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
        idx = -1
        min_distance = float('inf')
        for i, (X, Y) in enumerate(points):
            if X == x or Y == y:
                distance = abs(X - x) + abs(Y - y)
                if distance < min_distance:
                    min_distance = distance
                    idx = i
        return idx

Intersection of two arrays II

Topic link: 350. Intersection of Two Arrays II

image-20220419104148837

There are two approaches to this question, the following code uses the first one:

  • Dictionary: Use a dictionary to count the number of occurrences of each number in an array, and then traverse another array. If it appears in the first array and the number of times is more than the current number, insert it into the returned array
  • Sort + double pointer: sort both arrays, then create pointers to the heads of the two arrays, and judge whether the elements currently pointed to are consistent until an array is traversed
    • If it is consistent, insert this element into the returned array
    • If not, move the pointer to the smaller element backward by one
# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月19日
描述: https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
"""
from typing import List


class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        d = dict()
        # 统计nums1中的数据出现的次数
        for num in nums1:
            d[num] = d.get(num, 0) + 1

        ret = []
        # 统计nums2中数据出现的次数,如果在nums1中出现过就插入数组中
        for num in nums2:
            d[num] = d.get(num, 0) - 1
            if d[num] >= 0:
                ret.append(num)

        return ret

The best time to buy and sell stocks

Topic link: 121. The best time to buy and sell stocks

image-20220419112102557

There are two ways to do this:

  • The first is a direct violent loop, and the double loop can traverse all the situations once.
  • The second is to maintain a minimum price of the previous days, and then the maximum profit of the day is the price of the day minus the previous minimum price. If the difference is greater than the maximum profit, the maximum profit will be modified.
# -*- coding:utf-8
"""
作者: Jia
日期: 2022年04月19日
描述: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
"""
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = int(1e9)
        max_profit = 0
        for price in prices:
            if price < min_price:
                min_price = price
            elif price - min_price > max_profit:
                max_profit = price - min_price
        return max_profit

Guess you like

Origin blog.csdn.net/qq_46311811/article/details/124269369