Sword finger offer 1~3

Two dimensional array lookup

In a two-dimensional array (the length of each one-dimensional array is the same), each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.

A key:

  1. Array is empty
  2. Arrange order well
  3. The number on the right side of the upper row can also be larger than the number on the left side of the lower row

Sequential search

    def Find(self, target, array):
        # write code here
        if len(array)==0 or len(array[0])==0:
            return 0
        l=0
        r=len(array[0])-1
        for i in range(len(array)):
            if array[i][0]<=target<=array[i][-1]:
                for j in range(len(array[i])):
                    if array[i][j]==target:
                        return True
        return False

Two points search

    def Find(self, target, array):
        # write code here
        if len(array)==0 or len(array[0])==0:
            return 0
       
        for i in range(len(array)):
            if array[i][0]<=target<=array[i][-1]:
                l=0
                r=len(array[0])-1
                while(l<=r):
                    mid=l+(r-l)//2
                    if array[i][mid]<target :
                        l=mid+1
                    elif array[i][mid]>target:
                        r=mid-1
                    else:
                        return True
                      
        return False

Replace blank space

Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.

Direct substitution

    def replaceSpace(self, s):
        # write code here
        return s.replace(" ","%20")

regular expression

import re
class Solution:
    def replaceSpace(self, s):
        # write code here
        s=re.sub(r" ","%20",s)
        return s

Print linked list from end to end

Enter a linked list and return an ArrayList from the end to the end.

Simple list

def printListFromTailToHead(self, listNode):
        # write code here
        res=[]
        while listNode:
            res.append(listNode.val)
            listNode=listNode.next
        return res[::-1]

recursion

    def printListFromTailToHead(self, listNode):
        res=[]
        def printListnode(listNode):
            # write code here
            if listNode:
                printListnode(listNode.next)
                res.append(listNode.val)
        printListnode(listNode)
        return res

Posted by PoOP on Fri, 18 Oct 2019 11:16:20 -0700