给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

实例
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。
思路:从左到右遍历数组存在数字把是0的逐一的替换,左右更替,最后在遍历剩余的直接填写0就可以
class Solution:
def moveZeroes(self, nums):
if len(nums)<0:
return
pos = 0
for i in range(len(nums)):
if nums[i]: nums[pos]=nums[i]
pos = pos+1 for j in range(pos,len(nums)):
nums[j]=0
return nums
s=Solution()
nums = [1,3,0,2,0,5]
print(s.moveZeroes(nums))


第二种方法:遍历数组过程中存在数字的时候才交换0和数字的位置,不存在数字时point还是在0的位置,可以自己感受一下的,逻辑很简单,但是有点拐弯

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
point = 0
for i in range(len(nums)):
if nums[i]:
nums[point] , nums[i] = nums[i], nums[point]
point += 1

分析
这个相比于前两题就要花点心思了,看题目原话

“你最多可以完成 两笔 交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)”,这个参考上篇博客里的1, 2, 3这个例子,

执行过程依然是

第一天买入,第二天卖出,收入为1,然后第二天再买入,第三天再卖出,收入为1,累计收入为2,(交易两次)。

等同于第一天买入,第三天卖出(交易一次)。没规定必须交易几次。

但是两笔交易一定有先后。

在[1, 2, ...... n-1, n] 中可把两次交易分为[1, 2, ...... i] 和 [i, ...... n-1, n],这个分解过程是122中的思想,

接着分别计算[1, 2, ...... i] 和  [i, ...... n-1, n] 中的最大利润 f[i] 和 g[i],计算方法在121中得以体现

我们最后就是取出 max(f[i], g[i]) 就可以了

leetcode862. 和至少为 K 的最短子数组
返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K 。
如果没有和至少为 K 的非空子数组,返回 -1 。

示例 1: 输入:A = [1], K = 1 输出:1 示例 2: 输入:A = [1,2], K = 4 输出:-1 示例 3: 输入:A = [2,-1,2], K = 3 输出:3
#使用collections.deque模块版本
class Solution:
def shortestSubarray(self, A, K):
from collections import deque
startIndex = 0
totalSum = 0 #总和
minLen = -1
dequeMinus = deque() #存储和为负数区域
for i in range(len(A)):
totalSum += A[i]
if A[i] < 0 :
minusRangeSum = A[i]
n = i
m = i
while minusRangeSum < 0 and n >= startIndex:
n -= 1
minusRangeSum += A[n]
n += 1
while n <= startIndex and startIndex <= i:
totalSum -= A[startIndex]
startIndex +=1
while len(dequeMinus) > 0 and n <= dequeMinus[-1][0]:
dequeMinus.pop()
dequeMinus.append((n,m))
while totalSum >= K:
if minLen == -1:
minLen = i - startIndex + 1
else:
minLen = min(minLen, i - startIndex + 1)
totalSum -= A[startIndex]
startIndex += 1
while len(dequeMinus) > 0 and startIndex >= dequeMinus[0][0]:
a,b = dequeMinus.popleft()
while a <= startIndex and startIndex <= b:
totalSum -= A[startIndex]
startIndex += 1
return minLen
#使用list版本
class Solution:
def shortestSubarray(self, A, K):
startIndex = 0
totalSum = 0 #总和
minLen = -1
listMinus = [] #存储和为负数区域
for i in range(len(A)):
totalSum += A[i]
if A[i] < 0 :
minusRangeSum = A[i]
n = i
m = i
while minusRangeSum < 0 and n >= startIndex:
n -= 1
minusRangeSum += A[n]
n += 1
while n <= startIndex and startIndex <= i:
totalSum -= A[startIndex]
startIndex +=1
while len(listMinus) > 0 and n <= listMinus[-1][0]:
listMinus.pop()
listMinus.append((n,m))
while totalSum >= K:
if minLen == -1:
minLen = i - startIndex + 1
else:
minLen = min(minLen, i - startIndex + 1)
totalSum -= A[startIndex]
startIndex += 1
while len(listMinus) > 0 and startIndex >= listMinus[0][0]:
a, b = listMinus[0]
del(listMinus[0])
while a <= startIndex and startIndex <= b:
totalSum -= A[startIndex]
startIndex += 1
return minLen
 

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if(len(prices) <= 1):
return 0
buy_price = prices[0]
max_profit = 0
for i in range(1,len(prices)):
buy_price = min(buy_price, prices[i])
max_profit = max(max_profit, prices[i] - buy_price)
return max_profit

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
  随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
示例 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
  注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
  因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxpro = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
maxpro += prices[i] - prices[i-1]
return maxpro

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
  随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。  
  注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。  
  因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。

def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
len_prices = len(prices)
if len_prices < 2:
return 0 # 用来记录不同区间里的最大利润
f = [0] * len_prices
g = [0] * len_prices # 计算原则就是121的解
minf = prices[0]
for i in range(1, len_prices):
minf = min(minf, prices[i])
f[i] = max(f[i - 1], prices[i] - minf) maxg = prices[len_prices - 1]
for i in range(len_prices - 1)[::-1]:
maxg = max(maxg, prices[i])
g[i] = max(g[i], maxg - prices[i]) # 取其中最大值
maxprofit = 0
for i in range(len_prices):
maxprofit = max(maxprofit, f[i] + g[i]) return maxprofit

Leetcode 78. Subsets Python DFS 深度优先搜索解法

问题描述
Given a set of distinct integers, nums, return all possible subsets (the power set).
给定一个数据集合,求该集合的所有子集。
Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[3], 
[1], 
[2], 
[1,2,3], 
[1,3], 
[2,3], 
[1,2], 
[] 
]

思路
深度优先算法回溯:以【1,2,3】为例

每轮都传递一个数组起始指针的值,保证遍历顺序:

第一轮:先遍历以1 开头的所有子集,1→12→123 →13

第二轮:遍历以2开头的所有子集,2→23

第三轮:遍历以3开头的所有子集,3

这样三轮遍历保证能找到全部1开头,2开头,3开头的所有子集;同时,每轮遍历后又把上轮的头元素去掉,这样不会出现重复子集。(包括空集)

class Solution:
def subsets(self, nums): res = []
nums.sort()
def dfs(nums,index,path,res):
res.append(path) for i in range(index,len(nums)):
dfs(nums,i+1,path+[nums[i]],res)
dfs(nums,0,[],res)
return res
s = Solution()
nums = [1,2,3]
print(s.subsets(nums))

leetcode算法题121-123 --78 --python版本的更多相关文章

  1. LeetCode算法题-Design LinkedList(Java实现)

    这是悦乐书的第300次更新,第319篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第168题(顺位题号是707).设计链表的实现.您可以选择使用单链表或双链表.单链表中的 ...

  2. LeetCode算法题-Reverse String II(Java实现)

    这是悦乐书的第256次更新,第269篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第123题(顺位题号是541).给定一个字符串和一个整数k,你需要反转从字符串开头算起的 ...

  3. LeetCode算法题-K-diff Pairs in an Array(Java实现)

    这是悦乐书的第254次更新,第267篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第121题(顺位题号是532).给定一个整数数组和一个整数k,您需要找到数组中唯一的k- ...

  4. LeetCode算法题-Sum of Two Integers(Java实现)

    这是悦乐书的第210次更新,第222篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第78题(顺位题号是371).计算两个整数a和b的总和,但不允许使用运算符+和 - .例 ...

  5. LeetCode算法题-Implement Stack Using Queues

    这是悦乐书的第193次更新,第198篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第54题(顺位题号是225).使用队列实现栈的以下操作: push(x) - 将元素x推 ...

  6. LeetCode算法题-Best Time to Buy and Sell Stock

    这是悦乐书的第172次更新,第174篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第31题(顺位题号是121).假设有一个数组,其中第i个元素是第i天给定股票的价格.如果 ...

  7. LeetCode算法题-Remove Duplicates from Sorted List

    这是悦乐书的第160次更新,第162篇原创 01 前情回顾 昨晚的爬楼梯算法题,有位朋友提了个思路,使用动态规划算法.介于篇幅问题,这里不细说动态规划算法,以后会在数据机构和算法的理论知识里细说. 昨 ...

  8. LeetCode算法题-Plus One(Java实现)

    这是悦乐书的第156次更新,第158篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第15题(顺位题号是66).给定一个非空数字数组来表示一个非负整数,并给其加1.该数组已 ...

  9. 【算法】LeetCode算法题-Palindrome Number

    这是悦乐书的第144次更新,第146篇原创 今天这道题和回文有关,即从前往后和从后往前是一样的,如"上海自来水来自海上"就是一个回文字符串,如整数121就是回文数,这些都是和回文相 ...

  10. 【算法】LeetCode算法题-Reverse Integer

    这是悦乐书的第143次更新,第145篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第2题(顺位题号是7),给定32位有符号整数,然后将其反转输出.例如: 输入: 123 ...

随机推荐

  1. Eclipse 不能调试的问题

    现象 弹出 Cannot connect to VM Console 中的输出是: ERROR: transport error 202: connect failed: Connection ref ...

  2. Linux添加虚拟内存 && 修改Linux系统语言

    Linux添加虚拟内存 首先执行free -h查看内存状况: total used free shared buff/cache available Mem: 1.8G 570M 76M 8.4M 1 ...

  3. S7-300 实训3 异步电机正反转控制

    含有视频 方便以后查阅 参考书籍 跟我动手学 S7-300/400 PLC 第2版  廖常初 主编 实训3 异步电动机 正反转控制 步骤1 步骤2 在 cycle execution 前方 右击 插入 ...

  4. 官网英文版学习——RabbitMQ学习笔记(四)Work queues

    工作队列:把每个任务只发送给一个工作者. 上一篇我们是从一个指定的队列发送接收消息,在本文中,我们将创建一个工作队列,用于在多个工作者之间分配耗时的任务. 工作队列(即任务队列)背后的主要思想是避免立 ...

  5. Python自学之路

    2020年春节,受新型冠状病毒影响,整个春节假期,全国人民都在恐慌之中,为了避免大家上班相互传染,公司号召国家政策,开始上班日期延迟,在家呆的实在太无聊,突然感觉自己不能浪费这美好的时光,决定学习Py ...

  6. C++编程学习(八)new&delete动态内存分配

    前段时间楼主忙着期末大作业,停更了一段,今天刚好在做机器人课程的大作业时,和同组的小伙伴利用python做了工业机器人的在线编程,突然想起来很久没有阅读大型工程了,马上补上- 接下来的几篇博客主要是博 ...

  7. cf 762D. Maximum path

    天呢,好神奇的一个DP23333%%%%% 因为1.向左走1格的话相当于当前列和向左走列全选 2.想做走超过1的话可以有上下走替代.而且只能在相邻行向左. 全选的情况只能从第1行和第3行转移,相反全选 ...

  8. IPv6-isis配置

    ①:ipv6 unicast-routing——开启IPv6路由功能 ②:router isis word——开启ISIS进程 ③:is-type——可以修改路由器ISIS等级 ④:进入接口 ⑤:启用 ...

  9. ActorFramework教程对比及规划

    牢骚太盛防肠断,风物长宜放眼量. 一.引子 昨天的文章,本来就是想写写ActorFramework的教程内容,结果写着写着偏了,变成了吐槽. 首先,声明一下,自己从未参加过任何LabVIEW培训班,也 ...

  10. 139-PHP static后期静态绑定(二)

    <?php class test{ //创建test类 public function __construct(){ static::getinfo(); //后期静态绑定 } public s ...