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实现--排序和搜索、设计问题、数学及其他的更多相关文章

  1. LeetCode初级算法的Python实现--链表

    LeetCode初级算法的Python实现--链表 之前没有接触过Python编写的链表,所以这里记录一下思路.这里前面的代码是和leetcode中的一样,因为做题需要调用,所以下面会给出. 首先定义 ...

  2. LeetCode初级算法的Python实现--字符串

    LeetCode初级算法的Python实现--字符串 # 反转字符串 def reverseString(s): return s[::-1] # 颠倒数字 def reverse(x): if x ...

  3. LeetCode初级算法的Python实现--数组

    LeetCode初级算法的Python实现--数组 # -*- coding: utf-8 -*- """ @Created on 2018/6/3 17:06 @aut ...

  4. LeetCode初级算法的Python实现--动态规划

    动态规划的本质是递归:所以做题之前一定要会递归:递归式就是状态转移方程:这里将会介绍使用动态规划做题的思维方式. 统一的做题步骤: 1.用递归的方式写出代码:(此方法写的代码在leetcode中一定会 ...

  5. LeetCode初级算法--数组02:旋转数组

    LeetCode初级算法--数组02:旋转数组 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/ ...

  6. LeetCode初级算法--字符串01:反转字符串

    LeetCode初级算法--字符串01:反转字符串 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.ne ...

  7. LeetCode初级算法--链表01:反转链表

    LeetCode初级算法--链表01:反转链表 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/ ...

  8. LeetCode初级算法--动态规划01:爬楼梯

    LeetCode初级算法--动态规划01:爬楼梯 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net ...

  9. LeetCode初级算法--排序和搜索01:第一个错误的版本

    LeetCode初级算法--排序和搜索01:第一个错误的版本 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.cs ...

随机推荐

  1. Celery+redis实现异步

    目录 Celery+redis实现异步 安装redis 安装celery-with-redis 添加celery相关配置 创建异步运行任务tasks.py 启动 Celery+redis实现异步 安装 ...

  2. 使用Swagger处理Api的显示与隐藏

    一.在SwaggerConfig.cs中配置如下: c.DocumentFilter<ShowApiFilter>(); c.DocumentFilter<HideApiFilter ...

  3. [原]零基础学习SDL开发之在Android使用SDL2.0显示BMP叠加图

    关于如何移植在android上使用SDL,可以参考[原]零基础学习SDL开发之移植SDL2.0到Android 和 [原]零基础学习SDL开发之在Android使用SDL2.0显示BMP图 . 在一篇 ...

  4. 鲁宾斯坦说:"思维是在概括中完成的。"

    鲁宾斯坦说:"思维是在概括中完成的."

  5. Unity3D Shaderlab 学习记录

    unity3d 定制的表面着色器(Surface Shader)的标准输出结构是这种: struct SurfaceOutput  {  half3 Albedo; //反射率  half3 Norm ...

  6. UVa 1658 - Admiral(最小费用最大流 + 拆点)

    链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  7. UVa 10375 - Choose and divide(唯一分解定理)

    链接: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  8. CF13C Sequence

    嘟嘟嘟 偶然看到的这道题,觉得有点意思,就做了. 首先题里说修改后的数列只能出现修改前的数,那么状态之间的转移也就之可能在这些数之间. 令f[i][j]表示第 i 个数改成原序列第 j 小的数时的最小 ...

  9. BZOJ 3744: Gty的妹子序列 【分块 + 树状数组 + 主席树】

    任意门:https://www.lydsy.com/JudgeOnline/problem.php?id=3744 3744: Gty的妹子序列 Time Limit: 20 Sec  Memory ...

  10. Tomcat整体介绍

    来源 本文整理自 <Tomcat内核设计剖析>.<Tomcat结构解析> Tomcat 整体架构 ​ 如上图所示:包含了Tomcat内部的主要组件,每个组件之间的层次包含关系很 ...