• 剑指offer(1)数组找数 字符串空格替换


    1.数组找数

    描述:

    一个二维数组,从左到右递增,从上到下递增。要求找到给定整数。

    思路:

    将给定数x与右上角的数t相比,t<x时去掉这一行,t>x时去掉这一列。直到找到。PS:也可以与左下角的数字比较

    代码

    arr=[]
    n= eval(input('数组行和列:'))
    for i in range(n):
        temp=[]
        s=input('每一行:').split(' ')
        for j in range(len(s)):
            temp.append(int(s[j]))
        arr.append(temp)
    x=eval(input('find:'))
    print(arr)
    def findInarray(arr,n,x):
    
        rows=cols=n-1
        row=0
        col=n-1
        while rows>0 and cols>0 and arr is not None:
            t=arr[row][col]
            if x<t:
                cols-=1
                col-=1
            elif x>t:
                rows-=1
                row+=1
            elif x==t:
                return True
        return False
    if findInarray(arr, n, x):
        print("Find")
    else:
        print("NoFind")
    

    字符串空格替换

    描述:

    在O(n)时间内将字符串中的空格替换为%20,要求在原字符串上操作

    思路:

    先遍历一次字符串得到空格个数,每个空格,将字符串大小增大2,用两个指针,一个指向原字符串末尾,另一个指向修改后的字符串末尾,从后往前复制。

    代码:

    s=input('')
    
    cnt=0
    j=len(s)-1
    
    for it in s:
        if it==' ':
            cnt+=1
    s=list(s)
    #print(s)
    for i in range (cnt):
        s.append(' ')
        s.append(' ')
    k=len(s)-1
    
    #print(j,k)
    while j>=0:
        if s[j]!=' ':
            s[k]=s[j]
            k-=1
            j-=1
        else:
            j-=1
            s[k]='0'
            s[k-1]='2'
            s[k-2]='%'
            k-=3
    s=''.join(s)
    print(s)
    
    
    
  • 相关阅读:
    shell 脚本语法
    discuz pre_forum_postposition表说明
    PHP调试工具Xdebug安装配置教程
    检查用户头像状态的脚本
    PHP 性能监测
    Mysql 索引优化
    MySQL主从复制配置
    vue mixin 混入
    vue渲染方式:render和template的区别
    vue自定义指令directive Vue.directive() directives
  • 原文地址:https://www.cnblogs.com/void-lambda/p/12318443.html
Copyright © 2020-2023  润新知