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 ...
随机推荐
- spring data jpa update
一:在controller 加上: @Controller @RequestMapping("/user") public class UserController { @Aut ...
- 最全的select加锁分析(Mysql)
引言 大家在面试中有没遇到面试官问你下面六句Sql的区别呢 select * from table where id = ? select * from table where id < ? s ...
- 在windows、linux中开启nginx的Gzip压缩大大提高页面、图片加载速度<转>
为了降低tomcat服务的压力,把页面上的图片采用windows版的nginx进行加载,由于有些图片比较大,加载特别的慢,所以在nginx中打开了gzip的压缩功能.加载图片的速度快了很多. 通过站长 ...
- C#中关于@的用法
1. 加在字符串前面,字符串中的 \ 失去转义符的作用,直接写字符串而不需要考虑转义字符 string path = @"C:\Windows\"; // 如果不加 @,编译会提示 ...
- python 中的比较==和is
Python 中的比较:is 与 == 在 Python 中会用到对象之间比较,可以用 ==,也可以用 is .但是它们的区别是什么呢? is 比较的是两个实例对象是不是完全相同,它们是不是同一个对象 ...
- U3D 编辑器中sceneview下相机操作相关
前几天在项目中想要实现一个编辑器模式下的3D空间画线功能,几经周折,还是作废. 原因有:相机空间到世界空间转换问题对于Z值不清楚,U3D自定义坐标轴控制问题,射线与平面求交点不对, 一个关键问题是:编 ...
- MYSQL如何解决幻读
第一部分 首先要了解下mysql数据库的事务特征之一隔离级别: READ UNCOMMITTED(未提交读): 在READUNCOMMITTED级别,事务中的修改,即使没有提交,对其他事务也都是可见的 ...
- SSL协议(安全套接层协议)
SSL是Secure Sockets Layer(安全套接层协议)的缩写,可以在Internet上提供秘密性传输.Netscape公司在推出第一个Web浏览器的同时,提出了SSL协议标准.其目标是保证 ...
- 一个简单的dropdown(CSS+jquery)
by 司徒正美 .dropdown{ position: relative; } .dropdown div{ position: relative; width:200px; height:30px ...
- git工作操作步骤
上班开始,打开电脑,git pull:拉取git上最新的代码: 编辑代码,准备提交时,git stash:将自己编辑的代码暂存起来,防止git pull时与库中的代码起冲突,否则自己的代码就白敲了: ...