Python|Leetcode daily posting Part04

01: Ring linked list

Title description:
Give you the head node of a linked list head, and determine whether there is a ring in the linked list.

If there is a node in the linked list that can be reached again by continuously tracking nextthe pointer , then there is a cycle in the linked list. In order to represent the ring in a given linked list, the evaluation system internally uses an integer posto indicate the position where the end of the linked list is connected to the linked list (the index 0starts from ). Note: posNot passed as a parameter. Just to identify the actual situation of the linked list.

Returns true if there is a cycle in the linked list. Otherwise, returns false.

Example:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in a linked list whose tail is connected to the second node.

answer:

# 快慢指针
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False

        slow = head
        fast = head.next

        while slow != fast:
            if not fast or not fast.next:
                return False
            slow = slow.next
            fast = fast.next.next

        return True

02: Jumping Game

Title description:
Given an array of non-negative integers nums, you are initially located at the first index of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine whether you can reach the last subscript.

Example:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: You can skip 1step , 0reach the subscript from the subscript 1, and then 1jump 3to the last subscript.

answer:

# 贪心
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n, rightmost = len(nums), 0
        for i in range(n):
            if i <= rightmost:
                rightmost = max(rightmost, i + nums[i])
                if rightmost >= n - 1:
                    return True
        return False

03: Bracket generation

Title description:
The number nrepresents the logarithm of generating parentheses. Please design a function that can generate all possible and valid combinations of parentheses.

Example:
Input: n = 3
Output:["((()))","(()())","(())()","()(())","()()()"]

answer:

# 回溯
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n <= 0: return []
        res = []

        def dfs(paths, left, right):
            if left > n or right > left: return
            if len(paths) == n * 2:  # 因为括号都是成对出现的
                res.append(paths)
                return

            dfs(paths + '(', left + 1, right)  # 生成一个就加一个
            dfs(paths + ')', left, right + 1)

        dfs('', 0, 0)
        return res

04: Binary search

Title description:
Given nan ordered (ascending) integer array of elements numsand a target value target, write a function to search numsin target, if the target value exists, return the subscript, otherwise return -1.

Example:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9appears numsin and is subscripted4

answer:

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

05: Robbery

Title Description:
You are a professional thief planning to rob houses along the street. There is a certain amount of cash hidden in each room. The only restrictive factor that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by thieves on the same night, the system will automatically call the police. .

Given an array of non-negative integers representing the amount stored in each house, calculate the maximum amount you can steal in one night without triggering the alarm.

Example:
Input: [1,2,3,1]
Output: 4
Explanation: 1Steal and 3.

answer:

# 动态规划
class Solution:
    def rob(self, nums: List[int]) -> int:
        prev = 0
        curr = 0

        # 每次循环,计算“偷到当前房子为止的最大金额”
        for i in nums:
            # 循环开始时,curr 表示 dp[k-1],prev 表示 dp[k-2]
            # dp[k] = max{ dp[k-1], dp[k-2] + i }
            prev, curr = curr, max(curr, prev + i)
            # 循环结束时,curr 表示 dp[k],prev 表示 dp[k-1]

        return curr

06: Search a rotated sorted array

Title description:
An array of integers is arranged numsin ascending order, and the values ​​in the array are different from each other .

Before being passed to the function, a rotation is performed onnums some subscript unknown in advance , so that the array becomes (subscript counting from ) . For example, after rotation at the subscript it might become .k(0 <= k < nums.length)[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]0[0,1,2,4,5,6,7]3[4,5,6,7,0,1,2]

Give you the rotated array nums and an integer target, if the target value target exists in nums, return its subscript, otherwise return -1.

You must design an algorithm O(log n)with to solve this problem.

Example:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output:4

answer:

# 二分查找
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid
            if nums[0] <= nums[mid]:
                if nums[0] <= target < nums[mid]:
                    r = mid - 1
                else:
                    l = mid + 1
            else:
                if nums[mid] < target <= nums[len(nums) - 1]:
                    l = mid + 1
                else:
                    r = mid - 1
        return -1

07: Zigzag transformation

Title description:
Arrange a given character string saccording to the given number of lines numRows, Zfrom .

For example, when the input string is and the number of "PAYPALISHIRING"lines is 3, the arrangement is as follows:

P   A   H   N
A P L S I I G
Y   I   R

After that, your output needs to be read line by line from left to right to produce a new string, for example: "PAHNAPLSIIGYIR".

Please implement this function to convert a string to a specified number of rows:

string convert(string s, int numRows);
Example:
Input: s = "PAYPALISHIRING", numRows = 3
Output:"PAHNAPLSIIGYIR"

answer:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        n, r = len(s), numRows
        if r == 1 or r >= n:
            return s
        t = r * 2 - 2
        ans = []
        for i in range(r):  # 枚举矩阵的行
            for j in range(0, n - i, t):  # 枚举每个周期的起始下标
                ans.append(s[j + i])  # 当前周期的第一个字符
                if 0 < i < r - 1 and j + t - i < n:
                    ans.append(s[j + t - i])  # 当前周期的第二个字符
        return ''.join(ans)

08: The best time to buy and sell stocks Ⅱ

Title description:
You are given an integer array prices, where prices[i]represents ithe price of a certain stock on day .

On each day, you can decide whether to buy and/or sell stocks. You can only hold at most one share of stock at any one time . You can also buy first and sell later on the same day.

Returns the maximum .

Example:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: buy on 2day , 3sell on day 4; buy on day , 5sell on day

answer:

# 动态规划
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n<=1: return 0

        dp = [[None, None] for _ in range(n)]
        dp[0][0] = 0
        dp[0][1] = -prices[0]

        for i in range(1, n):
            dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
            dp[i][1] = max(dp[i-1][1], dp[i-1][0]-prices[i])

        return dp[-1][0]    # 返回最后一天且手上没有股票时的获利情况

09: The length of the last word

Title description:
You are given a string sconsisting of several words, separated by some space characters before and after the words. Returns the length of the last word in the string.

A word is the largest substring consisting of letters only, without any space characters.

Example:
Input: s = "Hello World"
Output: 5
Explanation: The last word is Worldand the length is 5.

answer:

class Solution(object):
    def lengthOfLastWord(self, s):
        return len(s.split()[-1])

10: Level order traversal of binary tree

Title description:
Given the root node of your binary tree root, return the sequence traversal of its node values. (ie layer by layer, visit all nodes from left to right).

Example:
insert image description here
Input: root = [3,9,20,null,null,15,7]
Output:[[3],[9,20],[15,7]]

answer:

# 广度优先遍历 + 递归
class Solution(object):
	def levelOrder(self, root):
		if not root:
			return []
		res = []
		def dfs(index, r):
			# 假设res是[ [1],[2,3] ], index是3,就再插入一个空list放到res中
			if len(res) < index:
				res.append([])
			#  将当前节点的值加入到res中,index代表当前层,假设index是3,节点值是99
			# res是[ [1],[2,3] [4] ],加入后res就变为 [ [1],[2,3] [4,99] ]
			res[index - 1].append(r.val)
			# 递归的处理左子树,右子树,同时将层数index+1
			if r.left:
				dfs(index + 1, r.left)
			if r.right:
				dfs(index + 1, r.right)
		dfs(1, root)
		return res

Guess you like

Origin blog.csdn.net/qq_60090693/article/details/128985735