LeetCode學習記錄(4 6)

2021-09-07 14:09:31 字數 2821 閱讀 7219

給定兩個大小為 m 和 n 的有序陣列 nums1 和 nums2。

請你找出這兩個有序陣列的中位數,並且要求演算法的時間複雜度為 o(log(m + n))。

你可以假設 nums1 和 nums2 不會同時為空。

示例 1:

nums1 = [1, 3]

nums2 = [2]

則中位數是 2.0

示例 2:

nums1 = [1, 2]

nums2 = [3, 4]

則中位數是 (2 + 3)/2 = 2.5

**展示:

class solution:

def findmediansortedarrays(self, nums1, nums2):

""":type nums1: list[int]

:type nums2: list[int]

:rtype: float

"""nums = nums1 + nums2

nums.sort()

length = len(nums)

if length == 2:

return (nums[0] + nums[1])/2

if length % 2 == 0:

return (nums[length // 2 - 1] + nums[(length // 2)])/2

return nums[length // 2]

給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。

示例 1:

輸入: 「babad」

輸出: 「bab」

注意: 「aba」 也是乙個有效答案。

示例 2:

輸入: 「cbbd」

輸出: 「bb」

解法:首先向字串的空位插入』#』,這樣可以避免奇偶長度分類。

然後也是掃一遍字串,主要是記錄了已訪問過的最右側字元maxright 和其對稱軸pos,並加利用,避免重複訪問。

時間o(n)。

**展示:

class solution:

def longestpalindrome(self, s):

""":type s: str

:rtype: str

"""s = '#'+'#'.join(s)+'#'

#例如'#a#b#a#'

pos = maxright = 0

rl = [0]*len(s) #rl是回文串半徑,如回文串長3,rl=1,回文串長5,rl=2

maxcenter = 0 #記錄最長回文中心序號

for i in range(len(s)):

if i=0 and i+rl[i]+1maxright: #更新maxright和i

maxright = rl[i] + i

pos = i

if rl[i] > rl[maxcenter]: #更新maxcenter

maxcenter = i

return s[maxcenter-rl[maxcenter]:maxcenter+rl[maxcenter]+1].replace('#','')

並不是很懂,隨後有時間再回來看

將乙個給定字串根據給定的行數,以從上往下、從左到右進行 z 字形排列。

比如輸入字串為 「leetcodeishiring」 行數為 3 時,排列如下:

l c i r

e t o e s i i g

e d h n

之後,你的輸出需要從左往右逐行讀取,產生出乙個新的字串,比如:「lciretoesiigedhn」。

請你實現這個將字串進行指定行數變換的函式:

string convert(string s, int numrows);

示例 1:

輸入: s = 「leetcodeishiring」, numrows = 3

輸出: 「lciretoesiigedhn」

示例 2:

輸入: s = 「leetcodeishiring」, numrows = 4

輸出: 「ldreoeiiecihntsg」

解釋:l d r

e o e i i

e c i h n

t s g

**展示:

class solution:

def convert(self, s, numrows):

""":type s: str

:type numrows: int

:rtype: str

"""str_length = len(s)

node_length = 2*numrows - 2

# 兩列之間的差

result = ""

if str_length == 0 or numrows == 0 or numrows == 1:

return s

for i in range(numrows): # 從第一行遍歷到最後一行

for j in range(i, str_length, node_length):

result += s[j] # 第一行和最後一行 還有普通行的整列數字

if i != 0 and i != numrows-1 and j - 2*i + node_length < str_length:

result += s[j-2*i+node_length] # 單列行的數字

return result

LeetCode學習記錄(10)

給定乙個字串 s 和乙個字元模式 實現支援 和 的正規表示式匹配。匹配任意單個字元。匹配零個或多個前面的元素。匹配應該覆蓋整個字串 s 而不是部分字串。說明 s 可能為空,且只包含從 a z 的小寫字母。p 可能為空,且只包含從 a z 的小寫字母,以及字元 和 示例 1 輸入 s aa p a 輸...

LeetCode題解 46 全排列

leetcode中國,注意需要登入。給定乙個沒有重複數字的序列,返回其所有可能的全排列。輸入 1,2,3 輸出 1,2,3 1,3,2 2,1,3 2,3,1 3,1,2 3,2,1 leetcode 給出本題難度中等。根據給出序列,列出全排列。根據樣例輸入資料 1,2,3 我去,這麼簡單,不就是回...

Leetcode題庫 46 全排列

author zzq software pycharm file permute.py time 2018 11 15 19 42 要求 給定乙個沒有重複數字的序列,返回其所有可能的全排列。示例 輸入 1,2,3 輸出 1,2,3 1,3,2 2,1,3 2,3,1 3,1,2 3,2,1 impo...