给定一个数组 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. leetcode1261 Find Elements in a Contaminated Binary Tree

    """ Given a binary tree with the following rules: root.val == 0 If treeNode.val == x ...

  2. NAND Flash驱动

    硬件原理及分析 管脚说明         Pin Name Pin Function R/B(RnB) The R/B output indicates the status of the devic ...

  3. 微信浏览器 UA

    mozilla/5.0 (linux; android 5.1.1; mi note pro build/lmy47v) applewebkit/537.36 (khtml, like gecko) ...

  4. Day 31:CSS选择器、常用CSS样式、盒子模型

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. JS - input输入框点击回车提交或者进行别的操作

    $("input").keydown(function(event){ if (event.keyCode == 13) {         /* 提交或者别的操作 */ } }) ...

  6. NumPy 排序、查找、计数

    章节 Numpy 介绍 Numpy 安装 NumPy ndarray NumPy 数据类型 NumPy 数组创建 NumPy 基于已有数据创建数组 NumPy 基于数值区间创建数组 NumPy 数组切 ...

  7. kafka的编程模型

    1.kafka消费者编程模型 分区消费模型 组(group)消费模型 1.1.1.分区消费架构图,每个分区对应一个消费者. 1.1.2.分区消费模型伪代码描述 指定偏移量,用于从上次消费的地方开始消费 ...

  8. Centos 7 x86_64 环境Python2.7升级Python3.7.4

    升级Python3.7.4 #安装补丁包yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel read ...

  9. caffe 官方demo python api

    Jupyter https://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/net_surgery.ipynb 涉及: - ...

  10. Caffe Install by Cmake in Ubuntu 18.04

    环境: Ubuntu 18.04 CUDA 10.0 cudnn opencv 3.0 见 https://www.cnblogs.com/xiaoniu-666/p/11907710.html -- ...