Day1 Running Sum of 1d Array/Find Pivot Index/用两个栈实现队列

today is the first day i practise interview questions online,exactly on leetcode, preparing for the future job interview in England, so I want to summarise the ideas and mistakes during the practice, which is really important for memorising knowledge in thess topics.

Perhaps it is a little difficult to me at first, as the poor foundition and hard professional words, however, i will never give uo this time, i always keep my loved person and life in mind, so i would pay more attention on work to realise the happy life in the future.

OK, let's begin 

 

 Running Sum of 1d Array

 简单的一维向量相加,使用循环遍历,按照数组中的排列顺序循环相加

class Solution(object):
    def runningSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in range(1,len(nums)):
            nums[i] += nums[i-1]
        return nums

724. Find Pivot Index 

找到中心点,使得左侧的整数相加等于右边的,并返回中心点在数组中的位置,如果没有就返回-1

 

 answer1: enumerate遍历函数,右侧之和=数组中所有数的和 - (左侧的数+当前的X值)

class Solution(object):
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        P_l = 0
        P_r = sum(nums)
        for i,x in enumerate(nums):
         
            if P_l == (P_r-P_l-x):
                return i
            P_l += x
        return -1

answer2: 使用len(nums)进行循环

class Solution:
    def pivotIndex(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sumL = 0
        sumR = sum(nums)
        for i in range(len(nums)):
            sumR -= nums[i]
            if sumL == sumR:
                return i
            sumL += nums[i]
        return -1

用两个栈实现队列

 

函数设计:
加入队尾 appendTail() : 将数字 val 加入栈 A 即可。
删除队首deleteHead() : 有以下三种情况。
当栈 B 不为空: B中仍有已完成倒序的元素,因此直接返回 B 的栈顶元素。
否则,当 A 为空: 即两个栈都为空,无元素,因此返回 -1 。
否则: 将栈 A 元素全部转移至栈 B 中,实现元素倒序,并返回栈 B 的栈顶元素。

class CQueue:
    def __init__(self):
        self.A, self.B = [], []

    def appendTail(self, value):
        self.A.append(value)

    def deleteHead(self):
        if self.B: return self.B.pop()
        if not self.A: return -1
        while self.A:
            self.B.append(self.A.pop())
        return self.B.pop()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值