leetcode题库解答源码(python3)
下面和大家分享本人在leetcode上已经ace的题目源码(python3): 本人会持续更新!~
class Leetcode_Solution(object):
def twoSum_1(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
'''
# 此解法复杂度为O(n^2)
new_nums = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
new_nums.append(i)
new_nums.append(j)
return new_nums
'''
# 此解法复杂度为O(n)
# 拓展:若解不唯一,可先将nums排序后进行下面操作,将全部符合对输出
if len(nums)<= 1:
return False
else:
dict = {}
for i in range(len(nums)):
# 字典底层是用hash表实现的,无论字典中有多少元素,查找的平云复杂度均为O(1)
if num[i] in dict:
return [dict[nums[i]], i]
else:
dict[target - nums[i]] = i
def reverse_7(self,x):
"""
:type x: int
:rtype: int
"""
MAX = 2**31 - 1
min = -1*2**31
if x < 0:
y = -1*int(str(-x)[::-1])
else:
y = int(str(x)[::-1])
if y > Max or y < min:
return 0
return y
def isPalindrome_9(self, x):
renum = 0
if x < 0 or (x % 10 == 0 and x != 0):
return False
while x > renum:
renum = renum * 10 + x % 10
x /= 10
return x == renum or x == renum/10
def romanToInt_13(self, s):
"""
:type s: str
:rtype: int
"""
dic = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
sum = 0
for i in range(len(s)-1):
if dic[s[i]] < dic[s[i+1]]:
sum -= dic[s[i]]
else:
sum += dic[s[i]]
return sum + dic[s[-1]]
def longestCommonPrefix_14(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0: # Horizontal scanning/////another way: vertical scanning
return ''
prefix = strs[0]
for i in range(1,len(strs)):
while strs[i].find(prefix) != 0:
prefix = prefix[0:len(prefix)-1]
if prefix == '':
return ''
return prefix
def isValid_20(self, s):
"""
:type s: str
:rtype: bool
"""
'''
list = []
a = b = c = 0
if len(s) == 0:
return True
for i in range(len(s)):
if s[i] == '(':
list.append(s[i])
a += 1
if s[i] == '{':
list.append(s[i])
b += 1
if s[i] == '[':
list.append(s[i])
c += 1
if s[i] == ')':
if len(list) != 0 and list[-1] == '(':
list.pop()
a -= 1
else:
return False
if s[i] == '}':
if len(list) != 0 and list[-1] == '{':
list.pop()
b -= 1
else:
return False
if s[i] == ']':
if len(list) != 0 and list[-1] == '[':
list.pop()
c -= 1
else:
return False
if len(list) == 0 and a == b == c == 0:
return True
else:
return False
'''
dic = {')':'(','{':'}','[':']'}
stack = []
for i in s:
if i in dic.values():
stack.append(i)
elif i in dic.keys():
if stack == [] or dic[i] != stack.pop():
return False
else:
return False
return stack == []
def mergeTwoLists_21(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
head = rear = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
rear.next = l1
l1 = l1.next
else:
rear.next = l2
l2 = l2.next
rear = rear.next
rear.next = l1 or l2
return head.next
def removeDuplicates_26(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
newtail = 0
for i in range(1,len(nums)):
if nums[i] != nums[newtail]:
newtail += 1
nums[newtail] = nums[i]
return newtail + 1
def removeElement_27(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = len(nums)
j = 0
if i == 0:
return 0
while j < i:
if nums[j] == val:
nums.pop(j)
i -= 1
else:
j += 1
return len(nums)
def strStr_28(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle) +1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
def searchInsert_35(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return len([x for x in nums if x < target])
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
leetcode题库解答源码(python3)的更多相关文章
- php+gd库的源码安装
php+gd库的源码安装 PHP+GD安装 一.下载软件 gd-2.0.35.tar.gz http://www.boutell.com/gd/ jpegsrc.v6b. ...
- python重试库retryiny源码剖析
上篇博文介绍了常见需要进行请求重试的场景,本篇博文试着剖析有名的python第三方库retrying源码. 在剖析其源码之前,有必要讲一下retrying的用法,方便理解. 安装: pip insta ...
- leetcode题库
leetcode题库 #题名题解通过率难度出现频率 1 两数之和 46.5%简单2 两数相加 35.5%中等3 无重复字符的最长子串 31.1%中等4 寻找两个有序数组的中位 ...
- 如何优雅的阅读 GitHub 上开源 js 框架和库的源码
如何优雅的阅读 GitHub 上开源 js 框架和库的源码 step 先总后分,即先了解一下啊框架的大体架构,又一个全局的认识,在选择某些和感兴趣的部分,仔细阅读,各个击破: 带着问题阅读,用到了什么 ...
- vue UI库iview源码解析(2)
上篇问题 在上篇<iview源码解析(1)>中的index.js 入口文件的源码中有一段代码有点疑惑: /** * 在浏览器环境下默认加载组件 */ // auto install if ...
- 小而美的Promise库——promiz源码浅析
背景 在上一篇博客[[译]前端基础知识储备--Promise/A+规范](https://segmentfault.com/a/11...,我们介绍了Promise/A+规范的具体条目.在本文中,我们 ...
- HTTP请求库——axios源码阅读与分析
概述 在前端开发过程中,我们经常会遇到需要发送异步请求的情况.而使用一个功能齐全,接口完善的HTTP请求库,能够在很大程度上减少我们的开发成本,提高我们的开发效率. axios是一个在近些年来非常火的 ...
- 云风协程库coroutine源码分析
前言 前段时间研读云风的coroutine库,为了加深印象,做个简单的笔记.不愧是大神,云风只用200行的C代码就实现了一个最简单的协程,代码风格精简,非常适合用来理解协程和用来提升编码能力. 协程简 ...
- 标准库path源码解读
先看标准库 作用:关于路径的一些实用操作 https://github.com/golang/go/blob/master/src/path/path.go 源码地址 func IsAbs func ...
随机推荐
- Docker 在 Linux 平台的安装 以及一些常见命令
1,添加,清理 yum 源,查看应用列表 1.1,yum install -y epel-release 1.2,yum clean all 1.3,yum list (可以不运行) 2,安装, 启 ...
- Shell 编程(函数)
声明函数 demoFun(){ echo "这是我的第一个 shell 函数!" } 函数名(){ ...函数体 } 在Shell中,调用函数时可以向其传递参数.在函数体内部,通过 ...
- 结构体中string成员的问题
在结构体中定义字符串的成员的时候要注意定义成string有时候,在某些程序中给成员赋值会崩溃,但是不确定到底什么情况会崩溃.运行报错如下: Program received signal SIGSEG ...
- shell流程控制与循环结构
shell脚本中的流程控制有if/else语句.case语句,循环结果包括for循环.while循环.until循环等内容. if语句 (1)最简单的if语句.使用格式有2种方式,分别如下 使用格式1 ...
- Python 字符串基本操作
字符串是Python的一种基本类型,字符串的操作包括字符串格式化输出.字符串的截取.合并,字符串的查找和替换等操作. 字符串定义 Python中有3种表示字符串的方法:单引号.双引号.三引号.引号使用 ...
- 简单实现"回车!=提交"(去除表单的回车即提交)
-------------------------------------------------------------------------------------------------- 实 ...
- JSP报错Syntax error, insert ";" to complete Statement
org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 7 in ...
- Delphi动态调用C++写的DLL
c++ DLL 文件,建议用最简单的c++编辑工具.不会加入很多无关的DLL文件.本人用codeblocks+mingw.不像 VS2010,DLL编译成功,调用的时候会提示缺其他DLL. 系统生成的 ...
- 在使用 #import <objc/message.h>时 xcode 报 :Too many arguments to function call, expected 0 , have * 解决方法
选中项目 - Project - Build Settings -
- workerman channel组件集群推送
<?phpuse Workerman\Worker; require_once '../../web/Workerman/Autoloader.php';require_once '../../ ...