当前位置:网站首页>Leetcode programming practice -- Tencent selected 50 questions (I)
Leetcode programming practice -- Tencent selected 50 questions (I)
2022-07-25 03:09:00 【C. Shimmer】
LeetCode Programming practice —— Selected by Tencent 50 topic ( One )
⋆ \star ⋆ Question no -2 ⋆ \star ⋆ difficulty - secondary
Topic link : https://leetcode-cn.com/problems/add-two-numbers/
subject : Two are given. Non empty The list of is used to represent two non negative integers . among , Their respective digits are based on The reverse Stored in , And each of their nodes can only store a Numbers . If , Let's add the two numbers together , A new list will be returned to represent their sum . You can assume that in addition to the numbers 0 outside , Neither of these numbers 0 start .
Prepare for questions :
- Introduction to linked list : Linked list ( l i n k e d l i s t ) (linked list) (linkedlist) It's a physical discontinuity 、 Non sequential data structures , By a number of nodes ( n o d e ) (node) (node) The composition of .
- Each node of the unidirectional linked list contains two parts , Part of it is the variables that hold the data d a t a data data , The other part is a pointer to the next node n e x t next next .
class Node:
def __init__(self,data);
self.data=data
self.next=None
- The first node in a linked list is called the header node , The last node is called the tail node , The tail node n e x t next next The pointer points to null .
- Unlike arrays that randomly look for elements by subscript , For one of the nodes in the linked list A A A , We can only base on nodes A Of n e x t next next Pointer to find the next node of this node B B B , And then according to the nodes B B B Of n e x t next next The pointer finds the next node C C C … …
- If you want to trace back to its predecessor through a node of the linked list , We use Double linked list . A two-way linked list is slightly more complex than a one-way linked list , Every node of it has d a t a data data and n e x t next next The pointer , It also has... Pointing to the front node p r e v prev prev The pointer .
- summary : The elements in the linked list can be stored anywhere in memory . Each element of the linked list stores the address of the next element , Thus, a series of random memory addresses are strung together . It's easy to add elements to a linked list : Just put it in memory , And store its address in the previous element .
Topic realization (pycharm Realization ):
#!/usr/bin/python3
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# Something like this needs to generate new listnode Using dummy nodes will make it easier to deal with the problems of ,
# Is to add an arbitrary node in front , Finally back to .next Can
# Actually ans and head It can be understood as a pointer to the same linked list , So for head The changes can also be reflected in ans On
# ans Used to output the last listnode,head Used to process traversal and generate new listnode
ans = head = ListNode(0)
digit = 0 # Mark carry
# When l1 And l2 When you haven't finished traversing , Traverse and add in turn , And add and to the result
while l1 and l2:
num = l1.val + l2.val + digit # Calculation l1 and l2 Sum on this digit
head.next = ListNode(num % 10) # Add the sum of both in single digits to the result head and ans in
digit = num // 10 # Mark carry , If there is carry 1, No carry is 0
head, l1, l2 = head.next, l1.next, l2.next # All linked lists are moved backward to achieve the traversal effect
# When l1 Execute the loop when it is long
while l1:
num = l1.val + digit
head.next = ListNode(num % 10)
digit = num // 10
head, l1 = head.next, l1.next
# When l2 Execute the loop when it is long
while l2:
num = l2.val + digit
head.next = ListNode(num % 10)
digit = num // 10
head, l2 = head.next, l2.next
# l1 and l2 Are traversed , Check whether there is carry in the highest bit , If so, join
if digit:
head.next = ListNode(digit)
# Returns the of the dummy node next
return ans.next
def listToListnode(l):
head = temp = ListNode(0)
for num in l:
temp.next = ListNode(num)
temp = temp.next
temp.next = None
return head.next
def listnodeToList(head):
ans = []
while head:
ans.append(head.val)
head = head.next
return ans
if __name__ == '__main__':
l1 = [2, 4, 3]
l2 = [5, 6, 4]
l1 = listToListnode(l1)
l2 = listToListnode(l2)
so = Solution()
ans = so.addTwoNumbers(l1, l2)
ans = listnodeToList(ans)
print(ans)
⋆ Question no -4 ⋆ difficulty - difficult
Topic link :https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
subject : Given two sizes m and n Ordered array of nums1 and nums2. Please find the median of these two ordered arrays , And the time complexity of the algorithm is required to be O(log(m + n)). You can assume nums1 and nums2 Will not be empty at the same time .
Topic realization :
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
m = len(nums1)
n = len(nums2)
nums1.extend(nums2)# Merge
nums1.sort()# Sort
if (m + n) & 1:# If it's odd Return to the median
return nums1[(m + n - 1) >> 1]
else:# Returns the average of the two median values
return (nums1[(m + n - 1) >> 1] + nums1[(m + n) >> 1]) / 2
⋆ Question no -5 ⋆ difficulty - secondary
Topic link :https://leetcode-cn.com/problems/longest-palindromic-substring/
subject : Given a string s, find s The longest palindrome substring in . You can assume s The maximum length of is 1000.
Topic realization :
class Solution:
def longestPalindrome(self, s: str) -> str:
count = len(s)
if count == 0 or count == 1:
return s
longestPalindromelen = 1
longestPalindromeStr = s[0:1]
dp = [[False] * count for i in range(count)]
for r in range(1, count):
for l in range(0, r):
if s[r] == s[l] and (r - l <= 2 or dp[l + 1][r - 1] == True):
dp[l][r] = True
if longestPalindromelen < r - l + 1:
longestPalindromelen = r - l + 1
longestPalindromeStr = s[l:l + longestPalindromelen]
return longestPalindromeStr
边栏推荐
- Openlayers draw circles and ellipses
- JS written test question -- promise, setTimeout, task queue comprehensive question
- Common methods of array
- Swiper4 is used to smooth longitudinal seamless scrolling. After clicking or dragging the mouse, the animation is not completely completed, the mouse moves out of the automatic rotation, and the dynam
- Stm32cubemx quadrature encoder
- The latest interview questions and analysis of software testing in 2022
- List type to string type
- Three ways to solve your performance management problems
- FLASH read / write problem of stm32cubemx
- Openlayers ol ext: Transform object, rotate, stretch, zoom in
猜你喜欢

Banana pie bpi-m5 toss record (2) -- compile u-boot

C: wechat chat software instance (wpf+websocket+webapi+entityframework)

Learning Record V
![[stm32f130rct6] idea and code of ultrasonic ranging module](/img/a6/1bae9d5d8628f00acf4738008a0a01.png)
[stm32f130rct6] idea and code of ultrasonic ranging module

DOM operation -- get elements and nodes

Import and export using poi

How to take the mold for the picture of 1.54 inch TFT st7789 LCD screen

Mark down learning

Wechat sports field reservation of applet completion works applet graduation design (8) graduation design thesis template

Select sort / cardinality sort
随机推荐
JS foundation -- data
[jailhouse article] certify the uncertified rewards assessment of virtualization for mixed criticality
JS written test question -- prototype, new, this comprehensive question
Chrome process architecture
Flink's study notes
Solve the error: could not find 'xxxtest‘
Learning Record V
Backtracking to solve subset problem
Common Oracle commands
New key points of ES6
Interview question -- event cycle
Unity refers to a variable in another class (its own instance)
mysql_ Case insensitive
[jailhouse article] scheduling policies and system software architectures for mixed criticality
The dolphin scheduler calls the shell script and passes multiple parameters
Daily three questions 7.16
JS construction linked list
Riotboard development board series notes (V) -- porting u-boot
JS written test question -- realize the flat function of array
Strategy mode, just read one article