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()