Sword finger offer exercise set

1, Search of two dimensional array In a two-dimensional array (the length of each one-dimensional array is the same), e...

1, Search of two dimensional array
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.

Idea: look up from the lower left corner. The element on the right is larger than this one, and the element on the top is smaller than this one. So, if target is smaller than this element, look up, and if target is larger than this element, look right. If there is a boundary, the target element does not exist in the 2D array.

# -*- coding:utf-8 -*- class Solution: # array 2D list def Find(self, target, array): rows=len(array)-1 cols=len(array[0])-1 i=rows j=0 while j<=cols and i>=0: if target<array[i][j]: i-=1 elif target>array[i][j]: j+=1 else: return True return False

2, Replace 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.

class Solution: # s source string def replaceSpace(self, s): return s.replace(" ","%20")

3, Print linked list from end to end

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

# -*- coding:utf-8 -*- # Implement a linked list class with only one value val and one next 'pointer to the next node' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # Returns a sequence of list values from the tail to the head, for example [1,2,3] def printListFromTailToHead(self, listNode): # write code here if listNode is None: return [] return self.printListFromTailToHead(listNode.next) + [listNode.val]

Stack solution:
1. First traverse the linked list elements to the stack
2. Pop up the stack again

# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # Returns a sequence of list values from the tail to the head, for example [1,2,3] def printListFromTailToHead(self, listNode): # write code here lst,lst_bak = [],[] if not listNode: return lst while listNode: lst.append(listNode.val) listNode = listNode.next while lst: lst_bak.append(lst.pop()) return lst_bak

4 February 2020, 12:23 | Views: 2423

Add new comment

For adding a comment, please log in
or create account

0 comments