每日一练 — 2021.12.28


一,K个一组翻转链表

1,程序简介

  • 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
  • k 是一个正整数,它的值小于或等于链表的长度。
  • 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

进阶:

  • 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
  • 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
  • 输入:head = [1,2,3,4,5], k = 2
  • 输出:[2,1,4,3,5]
示例 2:
  • 输入:head = [1,2,3,4,5], k = 3
  • 输出:[3,2,1,4,5]
示例 3:
  • 输入:head = [1,2,3,4,5], k = 1
  • 输出:[1,2,3,4,5]
示例 4:
  • 输入:head = [1], k = 1
  • 输出:[1]

提示:

列表中节点的数量在范围 sz 内
1 <= sz <= 5000
0 <= Node.val <= 1000
1 <= k <= sz

以下程序实现了这一功能,请你填补空白处内容:

class ListNode(object):
	def __init__(self, x):
		self.val = x
		self.next = None
class LinkList:
	def __init__(self):
		self.head=None
	def initList(self, data):
		self.head = ListNode(data[0])
		r=self.head
		p = self.head
		for i in data[1:]:
			node = ListNode(i)
			p.next = node
			p = p.next
		return r
	def	convert_list(self,head):
		ret = []
		if head == None:
			return
		node = head
		while node != None:
			ret.append(node.val)
			node = node.next
		return ret
class Solution(object):
	def reverseKGroup(self, head, k):
		if head is None:
			return None
		index = 0
		lead, last = 0, 0
		pos = head
		temp = ListNode(-1)
		temp.next = head
		head = temp
		start = head
		_________________;
		return head.next
	def reverseList(self, head, end):
		pos = head.next
		last = end
		next_start = pos
		while pos != end:
			head.next = pos
			last_pos = pos
			pos = pos.next
			last_pos.next = last
			last = last_pos
		return next_start
# %%
l = LinkList()
head = [1,2,3,4, 5]
l1 = l.initList(head)
s = Solution()
print(l.convert_list(s.reverseKGroup(l1, k = 2)))

2,程序代码

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 28 11:35:01 2021
Function:
@author: 小梁aixj
"""
class ListNode(object):
    def __init__(self, x):
        self.val=x
        self.next=None
class LinkList:
    def __init__(self):
        self.head=None
    def initList(self, data):
        self.head=ListNode(data[0])
        r=self.head
        p=self.head
        for i in data[1:]:
            node=ListNode(i)
            p.next=node
            p=p.next
        return r
    def convert_list(self,head):
        ret=[]
        if head == None:
            return
        node=head
        while node != None:
            ret.append(node.val)
            node=node.next
        return ret
class Solution(object):
    def reverseKGroup(self, head, k):
        if head is None:
            return None
        index = 0
        last=0
        pos=head
        temp=ListNode(-1)
        temp.next=head
        head=temp
        start=head
        while pos is not None:
            if index%k == k-1:
                last=pos.next
                start=self.reverseList(start, last)
                pos=start
            pos=pos.next
            index += 1
        return head.next
    def reverseList(self, head, end):
        pos=head.next
        last=end
        next_start=pos
        while pos != end:
            head.next=pos
            last_pos=pos
            pos=pos.next
            last_pos.next=last
            last=last_pos
        return next_start
#%%
l = LinkList()
head = [1,2,3,4,5]
l1 = l.initList(head)
s = Solution()
print(l.convert_list(s.reverseKGroup(l1, k = 2)))

3,运行结果

在这里插入图片描述

二,文本左右对齐

1,程序简介

  • 给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
示例 1:
  • 输入:nums1 = [1,3], nums2 = [2]
  • 输出:2
  • 解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
  • 输入:nums1 = [1,2], nums2 = [3,4]
  • 输出:2.5
  • 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
示例 3:
  • 输入:nums1 = [0,0], nums2 = [0,0]
  • 输出:0
示例 4:
  • 输入:nums1 = [], nums2 = [1]
  • 输出:1
示例 5:
  • 输入:nums1 = [2], nums2 = []
  • 输出:2

提示:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106

进阶

  • 你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?

以下程序实现了这一功能,请你填补空白处内容:

import math
from typing import List


class Solution:
    def findMedianSortedArrays(self, nums1: List[int],
                               nums2: List[int]) -> float:
        nums1Size = len(nums1)
        nums2Size = len(nums2)
        na = nums1Size + nums2Size
        ns = []
        i = 0
        j = 0
        m = int(math.floor(na / 2 + 1))
        while len(ns) < m:
            n = None
            if i < nums1Size and j < nums2Size:
                if nums1[i] < nums2[j]:
                    n = nums1[i]
                    i += 1
                else:
                    n = nums2[j]
                    j += 1
            elif i < nums1Size:
                n = nums1[i]
                i += 1
            elif j < nums2Size:
                n = nums2[j]
                j += 1
            ns.append(n)
        d = len(ns)
        if na % 2 == 1:
            return ns[d - 1]
        else:
            return _____________________;


# %%
s = Solution()
print(s.findMedianSortedArrays([1, 3], [2]))

2,程序代码

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 28 11:35:42 2021
Function:
@author: 小梁aixj
"""
import math
from typing import List

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        nums1Size = len(nums1)
        nums2Size = len(nums2)
        na = nums1Size + nums2Size
        ns = []
        i = 0
        j = 0
        m = int(math.floor(na / 2 + 1))
        while len(ns) < m:
            n = None
            if i < nums1Size and j < nums2Size:
                if nums1[i] < nums2[j]:
                    n = nums1[i]
                    i += 1
                else:
                    n = nums2[j]
                    j += 1
            elif i < nums1Size:
                n = nums1[i]
                i += 1
            elif j < nums2Size:
                n = nums2[j]
                j += 1
            ns.append(n)
        d = len(ns)
        if na % 2 == 1:
            return ns[d - 1]
        else:
            return (ns[d - 1] + ns[d - 2]) / 2.0
# %%
s = Solution()
print(s.findMedianSortedArrays([1, 3], [2]))#2
print(s.findMedianSortedArrays([1, 2], [3, 4]))#2.5

3,运行结果

在这里插入图片描述

三,寻找两个正序数组的中位数

1,程序简介

  • 给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
  • 你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ’ ’ 填充,使得每行恰好有 maxWidth 个字符。
  • 要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
  • 文本的最后一行应为左对齐,且单词之间不插入额外的空格。

说明:

单词是指由非空格字符组成的字符序列。
每个单词的长度大于 0,小于等于 maxWidth。
输入单词数组 words 至少包含一个单词。
示例1:
  • 输入:
    words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
    maxWidth = 16
  • 输出:
    [
    “This is an”,
    “example of text”,
    "justification. "
    ]
示例 2:
  • 输入:
    words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”]
    maxWidth = 16
  • 输出:
    [
    “What must be”,
    "acknowledgment ",
    "shall be "
    ]
  • 解释: 注意最后一行的格式应为 "shall be " 而不是 “shall be”
    因为最后一行应为左对齐,而不是左右两端对齐,第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:
  • 输入:
    words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
    “to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
    maxWidth = 20
  • 输出:
    [
    “Science is what we”,
    “understand well”,
    “enough to explain to”,
    “a computer. Art is”,
    “everything else we”,
    "do "
    ]

以下程序实现了这一功能,请你填补空白处内容:

class Solution(object):
	def fullJustify(self, words, maxWidth):
		"""
		:type words: List[str]
		:type maxWidth: int
		:rtype: List[str]
		"""
		res = []
		res_list = []
		curr = []
		count, pos = 0, 0
		while pos < len(words):
			word = words[pos]
			if len(word) > maxWidth:
				pos += 1
			if len(word) + count + len(curr)<= maxWidth:
				count += len(word)
				curr.append(word)
				pos += 1
			else:
				res_list.append(curr)
				curr = []
				count = 0
		if len(curr) > 0:
			res_list.append(curr)
		for index, curr in enumerate(res_list):
			text = ''
			remain = sum([len(t) for t in curr])
			if len(curr) == 1:
				text = curr[0] + ' ' * (maxWidth - remain)
			elif index == len(res_list) - 1:
				text = ' '.join(curr)
				text += ' ' * (maxWidth - remain - len(curr) + 1)
			else:
				___________________________;
			res.append(text)
		return res
if __name__ == '__main__':
	s = Solution()
	print (s.fullJustify(["Don't","go","around","saying","the","world","owes","you","a","living;","the","world","owes","you","nothing;","it","was","here","first."],30))

2,程序代码

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 28 11:36:09 2021
Function:
@author: 小梁aixj
"""
class Solution(object):
    def fullJustify(self, words, maxWidth):
        res = []
        res_list = []
        curr = []
        count, pos = 0, 0
        while pos < len(words):
            word = words[pos]
            if len(word) > maxWidth:
                pos += 1
            if len(word) + count + len(curr)<= maxWidth:
                count += len(word)
                curr.append(word)
                pos += 1
            else:
                res_list.append(curr)
                curr = []
                count = 0
        if len(curr) > 0:
            res_list.append(curr)
        for index, curr in enumerate(res_list):
            text = ''
            remain = sum([len(t) for t in curr])
            if len(curr) == 1:
                text = curr[0] + ' ' * (maxWidth - remain)
            elif index == len(res_list) - 1:
                text = ' '.join(curr)
                text += ' ' * (maxWidth - remain - len(curr) + 1)
            else:
                
                step = (maxWidth - remain) / (len(curr) - 1 )
                extra = (maxWidth - remain) % (len(curr) - 1 )
                for index in range(len(curr) - 1):
                    text += curr[index] + ' ' * int(step)
                    if extra > 0:
                       text += ' '
                       extra -= 1
                text += curr[-1]
                
            res.append(text)
        return res
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
if __name__ == '__main__':
	s = Solution()
	print (s.fullJustify(words, maxWidth))

3,运行结果

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁辰兴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值