Sword finger offer (jz31--jz40) python!!

Posted by johnpdmccall on Wed, 26 Jan 2022 18:15:45 +0100

Number of occurrences of 1 in jz31 integers (from 1 to the number of occurrences of 1 in n integers)

describe

Enter an integer n and find the number of occurrences of 1 in the decimal representation of N integers 1 ~ n
For example, the numbers 1, 10, 11, 12 and 13 containing 1 in 1 ~ 13 appear 6 times in total

thinking

Direct method: splice 1-n numbers into a string and traverse the number of 1. It is the simplest and direct method. The time complexity is close to kn. Basically feasible

The code is as follows:

def jz31(s):
	count=0
	t=''
	for i in range(len(s)):
		t+=str(i)
	for j in t:
		if j=='1':
			count+=1
	return count

jz32 arranges the array into the smallest number

describe

Enter a positive integer array, splice all the numbers in the array into a number, and print the smallest of all the numbers that can be spliced. For example, if you enter the array {3, 32321}, the minimum number that these three numbers can be arranged is 321323.

thinking

My idea: first sort the array, then compare the size according to the string, and finally output the smallest number.

The code is as follows:

def jz32(numbers):
	if numbers=[]:
		return ''
	numbers.sort()
	for i in range(len(numbers)-1):
		numbers[0]=minnumber(str(numbers[0]),str(numbers[0]))
		numbers.pop(1)
	return numbers[0]
def minnumber(a,b):
	if a+b<b+a:
		return a+b
	else:
		return b+a

jz33 ugly number

describe

N umbers containing only qualitative factors 2, 3 and 5 are called ugly numbers. For example, 6 and 8 are ugly numbers, but 14 is not because it contains quality factor 7. Traditionally, we regard 1 as the first Ugly Number. Find the nth Ugly Number in the order from small to large.

thinking

Set three pointers, representing that the array position can be multiplied by 2 or 3 or 5. Compare each time to select the smallest number.

The code is as follows:

def jz33(n):
	if n<=0:
		retunr 0
	result=[0 for _ in range(n)]
	result[0]=1
	a=0
	b=0
	c=0
	for i in range(1,n):
		result[i]=min(result[a]*2,min(result[b]*3,result[c]*5))
		if result[i]==result[a]*2:
			a+=1
		if result[i]==result[b]*3:
			b+=1
		if result[i]==result[c]*5:
			c+=1
	return result[n-1]

jz34 characters that appear only once for the first time

describe

Find the first character that appears only once in a string (0 < = string length < = 10000, all composed of letters), and return its position. If not, return - 1 (case sensitive) (counting from 0)

thinking

Use the dictionary to store the number of occurrences, and then traverse the string to see the characters that appear once

The code is as follows:

def jz34(s):
	if len(s)<=0:
		return -1
	dic={}
	for i in range(len(s)):
		if s[i] not in dic:
			dic[s[i]]=1
		else:
			dic[s[i]]+=1
	for j in range(len(s)):
		if dic[s[j]] ==1:
			return j
	return -1

Reverse pair in jz35 array

describe

Two numbers in the array. If the previous number is greater than the following number, the two numbers form an inverse pair. Enter an array and find the total number of reverse pairs P in this array. And output the result of P's modulus of 100000007. I.e. output P% 100000007

For 50% 50% 50% data, size ≤ 104size\leq 10^4size ≤ 104
For 100% 100% 100% data, size ≤ 105size\leq 10^5size ≤ 105

thinking

Violent solution: loop through both sides to find the logarithm in reverse order.
Simple solution: merge and sort???? I can't understand for the time being

jz36 the first common node of two linked lists

describe

Enter two acyclic single linked lists and find their first common node. (note that because the incoming data is a linked list, the prompt of error test data is displayed in other ways to ensure that the incoming data is correct)

thinking

The key is how to make two linked lists of the same length? You can splice the linked list and judge with two pointers.

The code is as follows:

def jz36(head1,head2):
	if not head1:
		return None
	if not head2:
		return None
	pre=head1
	later=head2
	while pre!=later:
		pre=pre.next
		later=later.next
		if pre!=later:
			if not pre:
				pre=head2
			if not later:
				later=head1
	return pre

The number of times jz37 numbers appear in an ascending array

describe

Counts the number of times a number appears in an ascending array.

thinking

Violent solution: directly traverse the array and output
Binary decomposition method: determine the upper and lower bounds, but it is not easy to determine, then the binary method finds a target value and looks it up before and after

The code is as follows:

def jz37(data,k): 
	left=0
	right=len(data)-1
	flag=0
	while left<right:
		mid=(left+right)//2
		if data[mid]<k:
			left=mid
		elif data[mid]>k:
			right=mid
		else:
			flag=mid
	pre=flag-1
	later=flag+1
	count=1
	while pre>=0:
		if data[pre]==k:
			count+=1
			pre-=1
	while later<=len(data)-1:
		if data[later]==k:
			count+=1
			later+=1
	return count

Depth of jz38 binary tree

describe

Enter a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing from root node to leaf node form a path of the tree, and the length of the longest path is the depth of the tree.

thinking

Recursively get the depth of the tree

The code is as follows:

def jz38(root):
	if not root:
		return 0
	left=jz38(root.left)
	right=jz38(root.right)
	return max(left,right)+1

jz39 balanced binary tree

describe

Enter a binary tree to judge whether the binary tree is a balanced binary tree.
Here, we only need to consider its balance, not whether it is a sorted binary tree
Balanced Binary Tree has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and both the left and right subtrees are a Balanced Binary Tree.

Note: we agree that an empty tree is a balanced binary tree.

thinking

According to the depth solution of the previous question, this cycle recursion is used to judge whether the depth is reasonable

The code is as follows:

def jz39(root):
	if not root:
		return True
	if abs(jz38(root.left)-jz38(root.right))>1:
		return False
	return jz39(root.left) and jz39(root.right)
def jz38(root):
	if not root:
		return 0
	left=jz38(root.left)
	right=jz38(root.right)
	return max(left,right)+1

Two numbers that appear only once in the jz40 array

describe

In an integer array, all but two numbers appear twice. Please write a program to find these two numbers that only appear once.

thinking

Dictionary traversal, loop finding, sorting

The code is as follows:

def jz40(numbers):
	dic={}
	li=[]
	for i in range(len(numbers)):
		if numbers[i] not in dic:
			dic[numbers[i]]=1
		else:
			dic[numbers[i]]+=1
	for j in numbers:
		if dic[j]==1:
			li.append(j)
	if li[0]>li[1]:
		temp=li[0]
		li[0]=li[1]
		li[1]=temp
	return li

Topics: Python Algorithm linked list Binary tree