1.给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
for j in range(nums.index(i) + 1, len(nums)):
if i + nums[j] == target:
return (nums.index(i),j)

2.给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# class Solution:
# # @return a ListNode
# def addTwoNumbers(self, l1, l2):
# if l1 is None:
# return l2
# elif l2 is None:
# return l1
# else:
# carry = 0
# ret = ListNode(0)
# ret_Last = ret
#
# while (l1 or l2):
# sum = 0
# if (l1):
# sum = l1.val
# l1 = l1.next
# if (l2):
# sum += l2.val
# l2 = l2.next
# sum += carry
# ret_Last.next = ListNode(sum % 10)
# ret_Last = ret_Last.next
# carry = (sum >= 10)
# if (carry):
# ret_Last.next = ListNode(1)
# ret_Last = ret.next
# del ret
# return ret_Last

3.给定一个字符串,找出不含有重复字符的最长子串的长度。

示例:

给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。

给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。

给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列  而不是子串。

# class Solution:
# def lengthOfLongestSubstring(self, s):
# """
# :type s: str
# :rtype: int
# """
# Num = 0
# for j in range(0, len(s)):
# ns = ''
# for i in s[j:]:
# if i not in ns:
# ns = ns + i
# num = len(ns)
# else:
# break
#
# if num > Num:
# Num = num
#
# return Num

 

4.给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 。

请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。

示例 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
# """
# length1 = len(nums1)
# length2 = len(nums2)
# total = length1 + length2
# print(total)
#
# alist = []
# while len(nums1) and len(nums2):
# if nums1[0] < nums2[0]:
# alist.append(nums1.pop(0))
# else:
# alist.append(nums2.pop(0))
# if nums1:
# alist += nums1
# else:
# alist += nums2
# print(alist)
# if total % 2 == 0:
# half = int(total / 2)
# return (alist[half] + alist[half-1])/2
# else:
# half = int(total // 2)
# return alist[half]

 

5.给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba"也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
s='#'+'#'.join(s)+'#'
ff = 0
RL=[0]*len(s)
MaxRight=0
pos=0
MaxLen=0
for i in range(len(s)):
if i<MaxRight:
RL[i]=min(RL[2*pos-i], MaxRight-i)
else:
RL[i]=1
#尝试扩展,注意处理边界
while i-RL[i]>=0 and i+RL[i]<len(s) and s[i-RL[i]]==s[i+RL[i]]:
RL[i]+=1
#更新MaxRight,pos
if RL[i]+i-1>MaxRight:
MaxRight=RL[i]+i-1
pos=i
#更新最长回文串的长度
# MaxLen=max(MaxLen, RL[i])
ss = s[i - RL[i] + 1:i + RL[i]]
ff = max(len(ss), ff)
if len(ss) >= ff:
a = ss a = a.replace('#','')
return a

6. 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

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

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释: P I N
A L S I G
Y A H R
P I
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
ff = []
j = -1
s = list(s)
for i in range(numRows):
ff.append([]) while s!=[]:
while j < numRows-1 and s!=[]:
j += 1
ff[j].append(s.pop(0)) while j > 0 and s!=[]:
j -= 1
ff[j].append(s.pop(0)) s = ''
for i in range(numRows):
s = s + ''.join(ff[i])
return s

 7.给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < -pow(2,31) or x > pow(2,31)-1:
return 0
s = str(x)
if len(s) == 1:
return x
s = s[::-1]
if s.startswith('0'):
s = s.lstrip('0')
if s.endswith('-'):
s = '-' + s.rstrip('-')
i = int(s)
if i < -pow(2,31) or i > pow(2,31)-1:
return 0
return i

 

9.判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = list(str(x)) s1 =list(str(x))
s1.reverse() if s1 == s:
return True
else:
return False

 

10.给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。

'.' 匹配任意单个字符。
'*' 匹配零个或多个前面的元素。

匹配应该覆盖整个字符串 (s) ,而不是部分字符串。

说明:

  • s 可能为空,且只包含从 a-z 的小写字母。
  • p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *

示例 1:

输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。

示例 2:

输入:
s = "aa"
p = "a*"
输出: true
解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重复 'a' 一次, 字符串可变为 "aa"。

示例 3:

输入:
s = "ab"
p = ".*"
输出: true
解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。

示例 4:

输入:
s = "aab"
p = "c*a*b"
输出: true
解释: 'c' 可以不被重复, 'a' 可以被重复一次。因此可以匹配字符串 "aab"。

示例 5:

输入:
s = "mississippi"
p = "mis*is*p*."
输出: false

 

class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
sLen = len(s)
pLen = len(p)
if (pLen == 0):
return sLen == 0
if (pLen == 1):
if (p == s) or ((p == '.') and (len(s) == 1)):
return True
else:
return False
#p的最后一个字符不是'*'也不是'.'且不出现在s里,p跟s肯定不匹配
if (p[-1] != '*') and (p[-1] != '.') and (p[-1] not in s):
return False
if (p[1] != '*'):
if (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
return self.isMatch(s[1:],p[1:])
return False
else:
while (len(s) > 0) and ((p[0]==s[0]) or (p[0]=='.')):
if (self.isMatch(s,p[2:])):
return True
s = s[1:]
return self.isMatch(s,p[2:])

 

11.给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (iai) 。画 n 条垂直线,使得垂直线 i 的两个端点分别为 (iai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

注意:你不能倾斜容器,n 至少是2。

class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
head = 0
tail = len(height) - 1
max_water = 0
while head < tail:
max_water = max(max_water, min(height[head], height[tail]) * (tail - head))
if height[head] < height[tail]:
head += 1
else:
tail -= 1
return max_water

 

14.编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
str=strs[0]
Min=len(str)
for i in range(1,len(strs)):
j=0
p=strs[i]
while j<Min and j<len(p) and p[j]==str[j]:
j+=1
Min = Min if Min<j else j
return str[:Min]

 

15.给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
# class Solution:
# def threeSum(self, nums):
# """
# :type nums: List[int]
# :rtype: List[List[int]]
# """
# diction = {}
# for num in nums:
# if num in diction:
# diction[num] += 1
# else:
# diction[num] = 1
#
# dictkey = diction.keys()
# pos, neg = [], []
# for p in dictkey:
# if p >= 0:
# pos.append(p)
# else:
# neg.append(p)
#
# sorted(pos)
# sorted(neg)
#
# rsts = []
# rst = []
# if 0 in dictkey and diction[0] > 2:
# rsts.append([0, 0, 0])
# pos.reverse()
# for p in pos:
# for n in neg:
# inverse = -(p + n)
# if inverse in dictkey:
# if (inverse == p or inverse == n) and diction[inverse] > 1:
# rst = [inverse, p, n]
# rsts.append(sorted(rst))
# if inverse > p or inverse < n:
# rst = [inverse, p, n]
# rsts.append(sorted(rst))
#
# return rsts

 

16.给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) <= 3:
return sum(nums) nums.sort()
maxSum = sum(nums[-3:])
minSum = sum(nums[:3]) if target <= minSum:
return minSum
if target >= maxSum:
return maxSum if target - minSum > maxSum - target:
closet = maxSum
distance = maxSum - target
else:
closet = minSum
distance = target - minSum for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1 while left < right: s = nums[i] + nums[left] + nums[right] if abs(s - target) < distance:
closet = s
distance = abs(s - target) if s > target:
if nums[i] + 2 * nums[left] > target:
break right -= 1 else:
if nums[i] + 2 * nums[right] < target:
break left += 1 return closet

17.给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution:
def __init__(self):
self.dt = {'1':'',
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz',
'0':''} def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0: return []
elif len(digits) == 1: return [s for s in self.dt[digits[0]]] elif len(digits) == 2:
return [a+b for a in self.dt[digits[0]] for b in self.dt[digits[1]]] else:
str_list = self.letterCombinations(digits[1:])
return [a+b for a in self.dt[digits[0]] for b in str_list]

  

LeetCode 答案(python)1-17的更多相关文章

  1. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  2. LeetCode专题-Python实现之第27题:Remove Element

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  3. LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode专题-Python实现之第21题:Merge Two Sorted Lists

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  5. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  6. LeetCode专题-Python实现之第9题:Palindrome Number

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  7. LeetCode专题-Python实现之第14题:Longest Common Prefix

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  8. LeetCode专题-Python实现之第13题:Roman to Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  9. LeetCode专题-Python实现之第7题:Reverse Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  10. LeetCode专题-Python实现之第1题:Two Sum

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

随机推荐

  1. [shell]如何测试shell脚本,保证正确

    如何用最快最有效的方式进行测试? 很多开发的习惯是,二话不说,写完/拿到,就跑一把,看看输入,输出,想要的操作是否完成,也就过了. 其实这是十分不严谨的,若是未经过QA,风险还是相当大的. 以下即sh ...

  2. 2019巅峰极客CTF-web1(LOL英雄联盟)

    今晚有空 以后随缘写博客了 好好沉淀 web1当天做出的队伍很少 其实不难    折腾到最后就差一步  可惜    0x01 读取文件 截图没留了 只留了代码部分. 有个页面  有上传和下载功能 起初 ...

  3. YouTube 网站的架构演进——阅读心得

    基础平台 Apache Python Linux(SuSe) MySQL psyco,一个动态的Python到C的编译器 lighttpd代替Apache做视频播放 状态 支持每天超过5亿的视频点击量 ...

  4. 【SVN】彻底 svn 服务器上的 删除某一个文件或文件夹

    参考: CSDN1:https://blog.csdn.net/u011729865/article/details/78764523 CSDN2:https://blog.csdn.net/wyyo ...

  5. API网关的用处

    API网关我的分析中会用到以下三种场景. Open API. 企业需要将自身数据.能力等作为开发平台向外开放,通常会以rest的方式向外提供,最好的例子就是淘宝开放平台.腾讯公司的QQ开发平台.微信开 ...

  6. 总结SQL查询慢的50个原因

    查询速度慢的原因很多,本文总结SQL查询慢的50个原因: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列导致查询不优 ...

  7. VBA 格式化excel数据表 (数据分列)

    Sub ImportData() ' ' Copy Data from one workbook to the Current Workbook ' Place the macro file in t ...

  8. Storm和Hadoop 区别

    Storm - 大数据Big Data实时处理架构   什么是Storm? Storm是:• 快速且可扩展伸缩• 容错• 确保消息能够被处理• 易于设置和操作• 开源的分布式实时计算系统- 最初由Na ...

  9. JAVA 基础编程练习题23 【程序 23 求岁数】

    23 [程序 23 求岁数] 题目:有 5 个人坐在一起,问第五个人多少岁?他说比第 4 个人大 2 岁.问第 4 个人岁数,他说比第 3 个 人大 2 岁.问第三个人,又说比第 2 人大两岁.问第 ...

  10. Oracle查询显示CLOB的内容

    select dbms_lob.substr(note)  from table