剑指offer 系列(一)二维数组中的查找,替换空格,从头到尾打印链表

平台:牛客,语言:python2.7

二维数组中的查找

题目描述

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

解题思路:

从左上角或右下角开始遍历,例如在右上角,如果数组中数比该数小,下移,如果数组中数比该数大,左移。

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        raw = len(array)
        col = len(array[0])
        i = 0
        j = col-1 
        #右上角
        while i<raw and j>=0:
            if array[i][j] > target:
                j -= 1
            elif array[i][j]< target:
                i += 1
            else:
                return True
        return False

替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ','%20')

 解题思路:

1.replace()函数 

2.从前往后遍历,遇到每一个空格,都要移动空格后所有字符串一次,从右往左遍历,每一个字符串只需要移动一次。

从头到尾打印链表

题目描述:

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

解题思路:

方法一:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []
        
        result = []
        while listNode.next is not None:
            result.extend([listNode.val])
            listNode = listNode.next
        result.extend([listNode.val]) 
        
        return result[::-1] 
    # 倒排使用extend,在尾部插入,不过输入数据多样化,有可能还是集合,所以转成列表。其实最关键在于[::-1]!!
    #这个方法效率应该还可以,先存入vector,再反转vector

方法二:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#头插法
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []
        
        result = []
        head = listNode
        
        while head:
            result.insert(0, head.val) #list.insert(index, obj) index为索引,obj为值
            head = head.next
        return result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值