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 ...
随机推荐
- png 2 icon
http://www.easyicon.net/covert/ 这个网页可以转换png图片为icon格式
- 使用ssh密钥登录虚拟主机里的另一台主机报警的解决方案
提示:Address 192.168.*.* maps to localhost, but this does not map back to the address - POSSIBLE BREAK ...
- 单件模式——Head First
一.定义 单件模式(Singleton Pattern)确保一个类只有一个实例,并提供一个全局访问点. 二.适用性 1.当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时. 2.当这个唯一实 ...
- Linux命令:history
显示历史(执行过的)命令. history [n] history -c history -d offset history -anrw [filename] history -p arg [arg ...
- Nginx反向代理时tomcat日志获取真实IP
对于nginx+tomcat这种架构,如果后端tomcat配置保持默认,那么tomcat的访问日志里,记录的就是前端nginx的IP地址,而不是真实的访问IP.因此,需要对nginx.tomcat做如 ...
- Spring/SpringBoot定义统一异常错误码返回
配置 大致说下流程, 首先我们自定义一个自己的异常类CustomException,继承RuntimeException.再写一个异常管理类ExceptionManager,用来抛出自定义的异常. 然 ...
- Matlab实现单层感知机网络识别字母
感知机网络的参数设置 % 具体用法: % net=newp(pr,T,TF,LF); % % pr: pr是一个R×2的矩阵,R为感知器中输入向量的维度(本例中使用35个字符表征一个字母,那么其维度为 ...
- Android EditText 操作。。。
EditText请求焦点三连击... editText.setFocusable(true); editText.setFocusableInTouchMode(true); editText.req ...
- UploadFtp
#!/bin/bash FILENAME=$ DSTDIR=$ FTPSRV=ip FTPUSER="user" FTPPWD="password" SRCDI ...
- Java 分页与原理(上)
Java web 实习需要用到分页技术 所以现在学习一下 做个记录 方便以后查阅 分类:传统分页技术 下拉式分页技术 起始位置(0)开始 查询(10条记录)