【牛客网】刷题记录

不断安更新
刷题顺序参考B站教程 https://space.bilibili.com/38725189?spm_id_from=333.788.b_765f7570696e666f.1 \url {https://space.bilibili.com/38725189?spm_id_from=333.788.b_765f7570696e666f.1} https://space.bilibili.com/38725189?spm_id_from=333.788.b_765f7570696e666f.1

注:不同于leecode,牛客网需要自己去写函数头

  1. 字符串最后一个单词长度

def func():
    words=input()
    words=words.split()
    if len(words)>5000 or len(words)==0:
        pass
    else:
        return len(words[-1])
   
print(func())
  1. 字符串个数统计
string_line=input()
kinds_count=set()

for i in string_line:
    if ord(i)>=0 and ord(i)<=127:
        kinds_count.add(i)

print(len(list(kinds_count)))
  1. 明明的随机数
while True:
    try:
        num_randint=int(input())
        randint_cnt=set()

        for i in range(num_randint):
            randint_cnt.add(int(input()))
        randint_cnt=list(randint_cnt)
        randint_cnt.sort()
        for i in randint_cnt:
            print(i)
    except:
        break
  1. 字符串分割
input_sequence=input()
string_list=[]
while len(input_sequence)>8:
    string_list.append(input_sequence[:8])
    input_sequence=input_sequence[8:]
if len(input_sequence)>0:
    string_list.append("{:0<8}".format(input_sequence))
for i in string_list:
    print(i)
  1. 输出一个16进制的字符串
input_int=int(input())
init_factor=2
if input_int<init_factor:
    print(init_factor+" ")
else:
    while input_int>=init_factor:
        k=input_int%init_factor
        if k==0:
            input_int/=init_factor
            print(str(init_factor)+' ',end='')
        else:
            init_factor+=1
            # 这里也是看得别人的trick,发现当因子到sqrt(int)之后就可以停止了。
            if(init_factor > input_int**(0.5)):
                print(str(int(input_int))+' ')
                break
 
  1. 合并链表记录
n=input()
dic={}
for i in range(int(n)):
    line=input().split()
    key=int(line[0])
    value=int(line[1])
    dic[key]=dic.get(key,0)+value
    
for i in dic:
    print(i,dic[i])
  1. 按照相反方向输出不重复的数字
def show_unredundant():
    input_list=input()[::-1]
    res=''
    for i in input_list:
        if i not in res:
            res+=i
    return res
print(show_unredundant())
  1. 数字颠倒
input_=str(input())
print(input_[::-1])
  1. 句子逆序
input_list=input().split(' ')[::-1]
print(' '.join(input_list))
  1. 按照字符串的长度对字符串进行排序

while True:
    try:
        ops=int(input())
        record=[]
        for i in range(ops):
            in_string=input()
            if in_string!='stop':
                record.append(in_string)
            elif in_string=='stop':
                break
            elif in_string[:-2]=='/n':
                break
        for i in sorted(record,key=len):
            print(i)
    except:
        break
  1. int 型正整数在存储中1的数目
input_integer=bin(int(input()))
cnt=0
for i in input_integer:
    if i=='1':
        cnt+=1
print(cnt)


下面个人随缘刷题

  1. 进制转换
  2. 两数之和
class Solution:
    def twoSum(self , numbers: List[int], target: int) -> List[int]:
        hash_map={}
        for seq,val in enumerate(numbers):
            hash_map[val]=seq
        for seq,val in enumerate(numbers):
            opptarget=target-val
            if opptarget in hash_map and seq!=hash_map[opptarget]:
                return [seq+1,hash_map.get(opptarget)+1]

  1. 明明的随机数

  2. 字符个数统计

  3. 跳台阶

  4. 二叉树的前序遍历
    方法一

class Solution:
    
        
    def preorderTraversal(self , root: TreeNode) -> List[int]:
        if root==None:
            return []
        
        s=[root]
        res=[]
        while(s):
            top_node=s[-1]
           s.pop()

            res.append(top_node.val)
            if top_node.right:
                s.append(top_node.right)
            if top_node.left:
                s.append(top_node.left)
        return res

方法二

class Solution:
    
    
    def preoreder(self,List,root):
        if root==None:
            return
        List.append(root.val)
        self.preoreder(List, root.left)
        self.preoreder(List, root.right)
        return List
    def preorderTraversal(self , root: TreeNode) -> List[int]:
        res=[]
        res=self.preoreder(res, root)
        return res
    
  1. 二叉树的全部遍历方法:
    前序遍历: root left_pointer right_pointer
    中序遍历: left_pointer root right_pointer
    后序遍历: left_pointer right_pointer root

  2. 二叉树后序遍历

#
class Solution:
    
    def postorder(self, list:List[int], root:TreeNode):
        
        if not root:
            return
        
        self.postorder(list, root.left)
        self.postorder(list, root.right)
        list.append(root.val)
    
    
    def postorderTraversal(self , root: TreeNode) -> List[int]:
        # write code here
        res=[]
        self.postorder(res, root)      
        return res
  1. 二叉树层序遍历
class Solution:
    def levelOrder(self , root: TreeNode) -> List[List[int]]:
        nodes=[root]
        res=[]
        while(nodes):
            res.append([i.val for i in nodes])
            n_update=[]
            for i in nodes:
                if i.left!=None:
                    n_update.append(i.left)
                if i.right!=None:
                    n_update.append(i.right)
            nodes=n_update
    
        return res
  1. 计算二叉树的最大深度
class Solution:
    def maxDepth(self , root: TreeNode) -> int:
        # write code here
        if not root:
            return 0
        nodes=[root]
        cnt=0
        while nodes:
            cnt+=1
            nodes_new=[]
            for i in nodes:
                if i.left!=None:
                    nodes_new.append(i.left)
                if i.right!=None:
                    nodes_new.append(i.right)
            nodes=nodes_new
        return cnt
  1. 按照之型打印链表
class Solution:
    def Print(self , pRoot: TreeNode) -> List[List[int]]:
        # write code here
        if not pRoot:
            return []
        nodes=[pRoot]
        res=[]
        index=0
        while(nodes):
            tmp=[]
            index+=1
            for i in range(len(nodes)):
                node=nodes[0]
                nodes=nodes[1:]
                if node.left!=None:
                    nodes.append(node.left)
                if node.right!=None:
                    nodes.append(node.right)
                tmp.append(node.val)
                
            if index%2==0 and index>=2:
                res.append(tmp[::-1])
            else:
                res.append(tmp)
        return res
  1. 判定一个二叉树从根节点到叶子节点的和为指定数值
class Solution:
    def hasPathSum(self , root: TreeNode, sum: int) -> bool:
        # write code here
        if not root:
            return False
        
        if not root.left and not root.right and root.val==sum:
            return True
        
        return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
class Solution:
    def hasPathSum(self , root: TreeNode, sum: int) -> bool:
        # write code here
        if not root:
            return False
        nodes=[root]
        while nodes:
            for i in  range(len(nodes)):
                node=nodes[0]
                if node.val==sum and not node.left and not node.right:
                    return True
                nodes=nodes[1:]
                if node.left:
                    node.left.val+=node.val
                    nodes.append(node.left)
                if node.right:
                    node.right.val+=node.val
                    nodes.append(node.right)
        return False

PS:第一种是前序遍历,第二种是层次遍历

  1. 缺失的第一个整数
class Solution:
    def minNumberDisappeared(self , nums: List[int]) -> int:
        # write code here
        nums.sort()
        pos_nums=[]
        for i in nums:
            if i>0:
                pos_nums.append(i)
        
        if pos_nums[0]>1:
            return 1
        else:
            if len(pos_nums)==1:
                return 2
        for i in range(len(pos_nums)-1):
            if pos_nums[i+1]-pos_nums[i]>1:
                return pos_nums[i]+1
            else:
                pass
        return pos_nums[-1]+1
  1. 利用hash表找到第一个没有出现的数字(
class Solution:
    def minNumberDisappeared(self , nums: List[int]) -> int:
        n = len(nums)
        mp = dict()
        #哈希表记录数组中出现的每个数字
        for i in range(n): 
            if nums[i] in mp:
                mp[nums[i]] += 1
            else:
                mp[nums[i]] = 1
        res = 1
        #从1开始找到哈希表中第一个没有出现的正整数
        while res in mp: 
            res += 1
        return res

数组中没有出现过的两个数

class Solution:
    def FindNumsAppearOnce(self , array: List[int]) -> List[int]:
        hash_map={}
        
        for i in array:
            if i not in hash_map:
                hash_map[i]=1
            else:
                hash_map[i]+=1
                
        hash_map=dict(sorted(hash_map.items(),key=lambda x:x[1]))
        res=[list(hash_map.keys())[0],list(hash_map.keys())[1]]
        res=sorted(res)
        return res
  1. 数组中出现次数超过数组长度一般的元素
class Solution:
    def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
        # write code here
        array_length=len(numbers)/2-1
        
        hash_map={}
        
        for i in numbers:
            if i in hash_map:
                hash_map[i]+=1
            else:
                hash_map[i]=0
        
        for i,j in hash_map.items():
            if j>array_length:
                return i
  1. 对称的二叉树
    相当于构建了一个对陈的二叉树,然后每一个元素依次对比
class Solution:
    def iter(self , left,right):
        if not left and not right:
            return True
        if not left or not right or left.val!=right.val:
            return False
        
        return self.iter(left.right, right.left) and self.iter(left.left, right.right)
    
    
    def isSymmetrical(self,root):
        return self.iter(root,root)
  1. 合并二叉树
    一种递归的方式去个
class Solution:
    def mergeTrees(self , t1: TreeNode, t2: TreeNode) -> TreeNode:
        # write code here
        
        if t1==None:
            return t2
        if t2==None:
            return t1
        
        head=TreeNode(t1.val+t2.val)
        head.left=self.mergeTrees(t1.left,t2.left)
        head.right=self.mergeTrees(t1.right,t2.right)
        
        return head
  1. 二叉树的镜像
class Solution:
    def Mirror(self , pRoot: TreeNode) -> TreeNode:
        # 空树返回
        if not pRoot: 
            return None
        # 先递归子树
        left = self.Mirror(pRoot.left) 
        right = self.Mirror(pRoot.right)
        # 交换
        pRoot.left = right 
        pRoot.right = left
        return pRoot

先递归子树然后交换左右子树。

  1. 判断是不是二叉搜索树
import sys
class Solution:
    pre=-sys.maxsize-1
    def isValidBST(self , root: TreeNode) -> bool:
        # write code here
        if not root:
            return True
        if not self.isValidBST(root.left):
            return False
        if root.val<=self.pre:
            return False
        self.pre=root.val
        if not self.isValidBST(root.right):
            return False
        return True

关于遍历二叉树,这里给一个代码可以直观地,看到树是如何遍历的

class TreeNode:
    def __init__(self,val,left=None,right=None):
        self.val=val
        self.left=left
        self.right=right

def build_tree():
		# 初始化所有的节点
    node1 =TreeNode(1)
    node2 =TreeNode(2)
    node3 =TreeNode(3)
    node4 =TreeNode(4)
    node5 =TreeNode(5)
    node6 =TreeNode(6)
    node7 =TreeNode(7)
    node8 =TreeNode(8)
    node9 =TreeNode(9)
    node10=TreeNode(10)
    node11=TreeNode(11)
    # 构建树
    node1.left=node2
    node1.right=node3
    node2.left=node4
    node2.right=node5
    node3.left=node6
    node3.right=node7
    node4.left=node8
    node4.right=node9
    node5.left=node10
    node5.right=node11
    return node1

def pre_order(node,res):
    if not node:
        return
    res.append(node.val)
    pre_order(node.left,res)
    pre_order(node.right,res)


def mid_order(node,res):
    if not node:
        return
    mid_order(node.left,res)

    res.append(node.val)

    mid_order(node.right,res)

def post_order(node,res):
    if not node:
        return
    post_order(node.left,res)
    post_order(node.right,res)
    res.append(node.val)

if __name__=="__main__":
    res=[]
    node=build_tree()
    pre_order(node,res)
    print("pre:",res)
    res=[]
    node=build_tree()
    mid_order(node,res)
    print("mid:",res)
    res=[]
    node=build_tree()
    post_order(node,res)
    print("post:",res)
  1. 判断二叉树是不是完全二叉树

完全二叉树指的是,除了最后一层以外,所有层皆为满叶子节点,并且最后一层的所有叶子节点都集中在最后一层的左侧。


class Solution:
    def isCompleteTree(self , root: TreeNode) -> bool:
        # write code here
        
        if not root:
            return True
        
        index=0
        
        queue=[root]

        while index < len(queue):
            if queue[index]:
                queue.append(queue[index].left)
                queue.append(queue[index].right)
            index+=1
        
        while queue[-1]==None:
            queue.pop()
        
        for i in queue:
            if i==None:
                return False
        return True
  1. 判断二叉树不是平衡树
#
class Solution:
    
    def deep(self,root):
        
        if not root:
            return 0
        
        left=self.deep(root.left)
        right=self.deep(root.right)
        
        return left+1 if left>right else right+1 
    
    def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
        
        if not pRoot:
            return True
        # write code here
        left_high=self.deep(pRoot.left)
        right_high=self.deep(pRoot.right)
        
        if abs(left_high-right_high)>1:
            return False
        
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
  1. 用两个栈实现pop 和 push
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    def push(self, node):
        self.stack1.append(node)
    def pop(self):
        # return xx
        while self.stack1:
            self.stack2.append(self.stack1.pop())
        res=self.stack2.pop()
        while self.stack2:
            self.stack1.append(self.stack2.pop())
        return res

包含min函数的栈

class Solution:
    stack=[]
    def push(self, node):
        self.stack=self.stack[::-1]
        self.stack.append(node)
        self.stack=self.stack[::-1]
    def pop(self):
        self.stack=self.stack[1:]
    def top(self):
        return self.stack[0]
    def min(self):
        return min(self.stack)
  1. 有效括号序列
class Solution:
    def isValid(self , s: str) -> bool:
        # write code here
        chars=[]
        for seq,val in enumerate(s):
            if val=='{':
                chars.append('}')
            elif val=='[':
                chars.append(']')
            elif val=='(':
                chars.append(')')
            elif (len(chars)==0):
                return False
            elif (chars[-1]==val):
                chars.pop()
                
        return len(chars)==0

华为机试题目

  1. 字符串逆序
input_string=input()
print(input_string[::-1])
  1. 求解立方根

    
def func(input_char):
    int_,flo=input_char.split('.')
    if int(flo[1])>=5:
        flo=int(flo[0])+1

    else:
        print(int_+'.'+flo[0])
        return 

    if int(flo)<10:
        print(int_+'.'+str(flo))
        return 
    if int(flo)>=10:
        flo=int(flo)
        flo=flo%10
        add_=flo//10
        int_=int(int_)+add_
        print(str(int_)+'.'+str(flo))

if __name__=='__main__':
    input_n=float(input())
    if input_n>0:
        input_char=str(input_n**(1/3))
    if input_n<0:
        input_char='-'+str((-input_n)**(1/3))
    func(input_char)
  1. 求最小公倍数
def func(input_):
    a,b=input_.split()
    a=int(a)
    b=int(b)
    if a%b==0 and a>=b:
        print(a)
        return

    if b%a==0 and b>=a:
        print(b)
        return

    common=1
    all_commons=[]
    while common<=a and common <=b:
        if a% common==0 and a>common and b%common==0 and b>common:
            all_commons.append(common)
        common+=1
    commons=1
    for c in all_commons:
        commons*=c
    print(a*b//commons)
func(input())
  1. 杨辉三角

首先可以根据下方的代码找到到指定层之前所有满足条件的选项。

def func(num_layers):
    if num_layers == 1:
        print(-1)
    elif num_layers == 2:
        print(-1)
    else:
        line2 = [1, 1, 1]
        window_size = 3
        last_layer = line2
        for i in range(num_layers):
            if i < 2:
                continue
            last_layer.append(0)
            last_layer = last_layer[::-1]
            last_layer.append(0)
            last_layer = last_layer[::-1]
            new_layer = [0] * len(last_layer)
            for i in range(len(last_layer) - 3 + 1):
                new_layer[i + 1] = sum(last_layer[i:i + 3])
            new_layer[0] = 1
            new_layer[-1] = 1
            last_layer = new_layer
        ops = 0
        for seq, val in enumerate(new_layer):
            if val >= 2 and val % 2 == 0:
                print(seq + 1)
                ops = 1
                break
        if not ops:
            print(-1)

if __name__=='__main__':
    for i in range(20):
        func(i+1)

然后发现从第三层开始,结果会遵循一定的规律:2 3 2 4 2 3 2 4 2 3 2 4 2 3 2 4 2 3 ,也就是2324重复循环。然后就可以通过下方的代码进行解决了

input_int=int(input())
if input_int==1 or input_int==2:
    print(-1)

else:
    ops=[2,3,2,4]
    
    print(ops[(input_int+2)%4-1])
  1. 表达式求值

正常求解为

print(eval(input()))

如果自己写一个方法,我的思路大致如下,先求括号内部,然后求括号外部。乘除优先加减其次,但是在分割字符串的时候方法需要完善,比如’10’不能分割成1和0


class Solution:
    
    stack1=[]
    stack2=[]
    
    def pre(self,input_):
        ops=['+','-','*','/']
        ele_storage=[]
        ops_storage=[]
        for i in input_:
            self.stack1.append(i)
        self.stack1=self.stack1[::-1]
        self.stacl1=self.preprocess(self.stack1)
        while self.stack1:
            element=self.stack1.pop()
            if element == '(':
                tmp=[]
                while element!=')':
                    element=self.stack1.pop()
                    if element!=')':
                        tmp.append(element)
                ele_storage.append(tmp)
            elif element in ops:
                ops_storage.append(element)
            
            else:
                ele_storage.append(element)
        start=0
        for i in range(len(ele_storage)):
            if isinstance(ele_storage[i], list):
                try:
                    ele_storage[i]=self.compute(ele_storage[i])
                except:
                    print(ele_storage)
        find_expres=[]
        for i in range(len(ops_storage)):
            find_expres.append(ele_storage[i])
            find_expres.append(ops_storage[i])
        find_expres.append(ele_storage[-1])
        try:
            res=self.compute(find_expres)
            return res
        except:
            return find_expres
    def preprocess(self,string_list):
				# 分割字符串的方法
        pass
    
    def compute(self,list_):
        list_ = list_[::-1]

        while "*" in list_:
            mul_location = list_.index("*")
            replace = int(list_[mul_location - 1]) * int(list_[mul_location + 1])
            new_list = []
            ops = 0
            for i in range(len(list_)):
                if i not in [mul_location - 1, mul_location, mul_location + 1]:
                    new_list.append(list_[i])
                if i in [mul_location - 1, mul_location, mul_location + 1] and not ops:
                    new_list.append(replace)
                    ops=1
            list_ = new_list

        while "/" in list_:

            mul_location = list_.index("/")
            replace = int(list_[mul_location - 1]) * int(list_[mul_location + 1])
            new_list = []
            ops = 0
            for i in range(len(list_)):
                if i not in [mul_location - 1, mul_location, mul_location + 1]:
                    new_list.append(list_[i])

                if i in [mul_location - 1, mul_location, mul_location + 1] and not ops:
                    new_list.append(replace)
                    ops = 1
            list_ = new_list
        cnt = int(list_.pop())
        while list_:
            ops = list_.pop()
            ele2 = list_.pop()
            if ops == "+":
                cnt += int(ele2)
            if ops == '-':
                cnt -= int(ele2)

        return cnt

S=Solution()
print(S.pre(input()))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值