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 ...
随机推荐
- linux命令整理
Linux系统命令 1. ls 查看某个 目录下 所有文件的大小总和 ls -lR| awk 'BEGIN{size=0;} /^[-l]/{size+=$5;print $0;} END{print ...
- selenium 滑动解锁(drag_and_drop_by_offset)
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from ...
- AngularJs学习笔记--I18n/L10n
原版地址:http://code.angularjs.org/1.0.2/docs/guide/i18n 一.I18n and L10n in AngularJS 1. 什么是I18n和L10n? 国 ...
- Mycat数据库中间件对Mysql读写分离和分库分表配置
Mycat是一个开源的分布式数据库系统,不同于oracle和mysql,Mycat并没有存储引擎,但是Mycat实现了mysql协议,前段用户可以把它当做一个Proxy.其核心功能是分表分库,即将一个 ...
- 十.mysqld_multi stop无效问题
今天在尝试运行mysqld_report stop的时候,发现无法停止mysql,日志中的错误如下 Stopping MySQL servers mysqladmin: [Warning] Using ...
- HDU 1698 【线段树,区间修改 + 维护区间和】
题目链接 HDU 1698 Problem Description: In the game of DotA, Pudge’s meat hook is actually the most horri ...
- 2.spring:集合属性
1.list 配置java.util.List类型的属性,需要指定<list>标签,在标签里面包含有一些元素,这些标签 可以通过<value>指定简单的常量值,通过<r ...
- 关于Ftp服务器
步骤/方法 首先在本地机器上创建一个用户!这些用户是用来登录到FTP的!我的电脑右键->管理->本地用户和组->用户->“右键”新建用户->输入用户名和密码再点创建就行了 ...
- Java之生成Pdf并对Pdf内容操作
虽说网上有很多可以在线导出Pdf或者word或者转成png等格式的工具,但是我觉得还是得了解知道是怎么实现的.一来,在线免费转换工具,是有容量限制的,达到一定的容量时,是不能成功导出的;二来,业务需求 ...
- 自定义的打印语句NSLog在控制台输出不完整的完美解决
// 打印日志 debug #ifdef DEBUG // 调试状态, 打开LOG功能 #define APPLog( s, ... ) printf("class: <%p %s:( ...