LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他
LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他
1、排序和搜索
class Solution(object):
# 合并两个有序数组
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
nums1[m:m + n] = nums2[:n]# 合并数组
nums1.sort()
# 第一个错误的版本
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
minn=1
maxn=n
while True:
mid=int((minn+maxn)/2)# 二分
if isBadVersion(mid)==True and isBadVersion(mid+1)==True:
maxn=mid-1
elif isBadVersion(mid)==False and isBadVersion(mid+1)==False:
minn=mid+1
else:
return mid+1
2、设计问题
打乱一个没有重复元素的数组。
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.numsR = nums[:]
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
self.nums = self.numsR[:]
return self.nums
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
random.shuffle(self.nums)
return self.nums
# 最小栈
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.nums = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.nums.append(x)
def pop(self):
"""
:rtype: void
"""
self.nums.pop(len(self.nums) - 1)
def top(self):
"""
:rtype: int
"""
return self.nums[(len(self.nums) - 1)]
def getMin(self):
"""
:rtype: int
"""
return min(self.nums)
3、数学
import random
class Solution(object):
# Fizz Buzz
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
strList = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
strList.append("FizzBuzz")
elif i % 3 == 0:
strList.append("Fizz")
elif i % 5 == 0:
strList.append("Buzz")
else:
strList.append(str(i))
return strList
# 计数质数,将当前该数的的倍数标记,则未被标记的位置为质数,因为当前该数不是前面的数的倍数
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
flag = [False for i in range(n + 1)]
for i in range(2, n):
if flag[i] == False:
k = i
while k <= n:
flag[k] = True
k += i
count += 1
return count
# 3的幂
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
while n > 1:
n = n / 3.0
if n != int(n):
return False
return True
# 罗马数字转整数
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
val = 0
data = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, }
for i in range(0, len(s)): # 如果遍历到最后一个字符或者当前字符代表的数大于后一个字符代表的数则加,反之减
if len(s) == i + 1 or data[s[i + 1]] <= data[s[i]]:
val += data[s[i]]
else:
val -= data[s[i]]
return val
4、其他
class Solution(object):
# 位1的个数
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res = bin(n).count('1')
return res
# 汉明距离
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xbin = bin(x)[2:]
ybin = bin(y)[2:]
count = 0
if len(xbin) > len(ybin): # 得到长度较短的
xbin, ybin = ybin, xbin
cha = len(ybin) - len(xbin)
for i in range(0, cha): # 将较短的用0补全
xbin = '0' + xbin
for i in range(0, len(ybin))[::-1]:
if xbin[i] != ybin[i]: # 判断
count += 1
return count
# 颠倒二进制位
def reverseBits(self, n):
nbin = bin(n)[2:]
for i in range(0, 32 - len(nbin)):
nbin = '0' + nbin
nbin = nbin[::-1]
result = int(nbin, 2) # 转十进制
return result
# 帕斯卡三角形
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
result = [[1]]
for i in range(1, numRows):
block = [1]
for j in range(0, i - 1):
block.append(result[i - 1][j] + result[i - 1][j + 1])
block.append(1)
result.append(block)
return result
# 有效的括号
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
while len(s) >= 0: #
flag = False # 标志如果下面三个都不存在 说明不是有效果括号,有的话则替换
if s.__contains__('()'):
s = s.replace('()', '')
flag = True
if s.__contains__('{}'):
s = s.replace('{}', '')
flag = True
if s.__contains__('[]'):
s = s.replace('[]', '')
flag = True
if len(s) == 0:
return True
if flag == False:
break
return False
# 缺失数字
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort() # 排序
for i in range(0, len(nums) - 1):
if (nums[i] + 1) != nums[i + 1]: # 如果当前值加一等于下一个
return nums[i] + 1
if nums[0] > 0:
return 0
return len(nums)
LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他的更多相关文章
- LeetCode初级算法的Python实现--链表
LeetCode初级算法的Python实现--链表 之前没有接触过Python编写的链表,所以这里记录一下思路.这里前面的代码是和leetcode中的一样,因为做题需要调用,所以下面会给出. 首先定义 ...
- LeetCode初级算法的Python实现--字符串
LeetCode初级算法的Python实现--字符串 # 反转字符串 def reverseString(s): return s[::-1] # 颠倒数字 def reverse(x): if x ...
- LeetCode初级算法的Python实现--数组
LeetCode初级算法的Python实现--数组 # -*- coding: utf-8 -*- """ @Created on 2018/6/3 17:06 @aut ...
- LeetCode初级算法的Python实现--动态规划
动态规划的本质是递归:所以做题之前一定要会递归:递归式就是状态转移方程:这里将会介绍使用动态规划做题的思维方式. 统一的做题步骤: 1.用递归的方式写出代码:(此方法写的代码在leetcode中一定会 ...
- LeetCode初级算法--数组02:旋转数组
LeetCode初级算法--数组02:旋转数组 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/ ...
- LeetCode初级算法--字符串01:反转字符串
LeetCode初级算法--字符串01:反转字符串 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.ne ...
- LeetCode初级算法--链表01:反转链表
LeetCode初级算法--链表01:反转链表 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/ ...
- LeetCode初级算法--动态规划01:爬楼梯
LeetCode初级算法--动态规划01:爬楼梯 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net ...
- LeetCode初级算法--排序和搜索01:第一个错误的版本
LeetCode初级算法--排序和搜索01:第一个错误的版本 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.cs ...
随机推荐
- %02hhX
大家经常会遇到将 调试信息例如从网络收到的数据包 或者 转换后的数据 打印出来,调试问题. 如果以ascii码打印的话,控制字符和ascii码以外的字符不能很好的查看具体值(看不到,或者乱码,尤其对于 ...
- 第五周 day5 python学习笔记
1.软件开发的常规目录结构 更加详细信息参考博客:http://www.cnblogs.com/alex3714/articles/5765046.html 2.python中的模块 ...
- 深入编解码:ASCII,UNICODE,UTF8等
ASCII ASCII = American Standard Code for Information Interchange(美国信息交换标准码) 美国最先有了计算机技术,计算机里面只有01,也就 ...
- 如何使用cntlm配置代理上网
https://blog.csdn.net/SdustLiYang/article/details/7034974 https://blog.csdn.net/bluishglc/article/de ...
- 保存头像- vue项目-base64字符串转图片
<img :onerror="errpic" class="customerHead" :src="param.customerHead&quo ...
- 【JAVA EE企业级开发四步走完全攻略】
本文是J2EE企业级开发四步走完全攻略索引,因内容比较广泛,涉及整个JAVA EE开发相关知识,这是一个长期的计划,单个发blog比较零散,所以整理此索引,决定以后每发一季JAVA EE blog后会 ...
- CodeIgniter框架学习要点
以下内容从兄弟连的CI教学视频中摘抄: http://codeigniter.org.cn/tutorials/ ------------------------------------------- ...
- HDU 5724 Chess(SG函数)
Chess Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submi ...
- LayIM项目之基础数据获取代码优化,Dapper取代ADO.NET
前言 最近在开发LayIM融云版,也在进行项目重构,现在在看之前的代码,简直不敢直视.不过不知道以后看现在的代码是不是也是糟糕的一批.LayIM有个接口,一般接触过的开发人员都不会生疏,就是init接 ...
- 解决SVN UUID客户端和服务器不一致的问题
下面是从别的文章中COPY过来的两篇文章,可以完美的解决这个问题: 一. 重新定位SVN的时候,遇到uuid不一致的问题. Google得知可以使用以下命令 有到svnadmin命令:(位于 SVN安 ...