friendly Tips, expand the above directory to see specific topics.
Arrange ordinal
Gives an arrangement that does not contain duplicate numbers, and asks for the number of all permutations of these numbers, sorted by dictionary order. Where the numbering starts at 1. Examples
For example, arranging [1,2,4] is the 1th arrangement. [2,1,4] is the 3rd arrangement
Analysis: This problem uses factorial, the length of the array is n, then there are N. Arrangement of the method.
To calculate the ordinal of an arrangement, as long as one traverses the arrangement, the first number corresponds to the subscript in the sorted array as I, then its front has i * (n-1). Kind of arrangement. The number is then pop out of the queue, and the number in the corresponding sorted array is moved out of the queue. So traversing down, the result is out.
Class Solution:
# @param {int[]} A an integer array
# @return {long} A long integer
def permutationindex (self, A):
# B is a sort of array
b=sorted (a)
Length=len (a)
if length==0: return
0
result=1 for
i in range ( 0,length):
Result=result + b.index (a[0)) * Self.factor ((length-1-i))
B.pop (B.index (a[0))) #要注意, B first out of the queue, A after the queue.
a.pop (0) return result
def factor (self,n):
result=1 to I in
Range (1,n+1):
result*=i return result
Simplifying Paths
Given the full path of a document (Unix-style), make a path simplification. Examples
"/home/", => "/home"
"/a/./b/." /.. /c/", =>"/C "
This problem is not difficult, but too thin, can not imagine the processing path have so many situations.
The only thing to be aware of is handling ". /"This path, once present in this form, means that the path before it is deleted."
I'm dealing with a split array, first the path to "/.... /"for the benchmark split into two parts, note must be split once."
So we get an array of two strings, and in the first string we divide it by the reference to "/", and the last element is to be deleted.
After the deletion, then put the path together, so that the loop processing, "... /"There is no more."
Class Solution:
# @param {string} path the original path
# @return {string} The simplified path
def Simplifypa Th (self, Path):
# Write Your code here
if '/./' in Path:
path=path.replace ("/./", "/")
Path=path.rstrip ("/")
While '//' in Path:
path=path.replace ("//", "/")
if "/..." Not in Path:
Path=path.rstrip (".")
If path== ": Return
"/"while
"/... /"In Path:
pathlist=path.split ("/..) /", 1)
pathlist0=pathlist[0].split ("/")
Pathlist0[len (pathList0) -1]="
pathlist[0]= "/". Join ( PATHLIST0)
path= "". Join (PathList) return
path
Maximum number
Gives a set of nonnegative integers, rearranging their order to form a maximum integer. Attention Matters
The final result can be very large, so we return a string to replace the integer. Have you ever met this problem in a real interview? Yes sample
Given [1, 20, 23, 4, 8], the integer that returns the largest combination should be 8423201.
This question is really wonderful, thought for a long time, finally solved with own method.
Class Solution: # @param num:a List of non negative integers # @return: A string def largestnumber (self, num):
# for [1, 20, 242, 23, 4, 8], divided into 10 groups, each group to find the maximum length of the number (for example, 2 of the maximum length of 242, length of 3) # for the length of data is not long enough to fill it to the longest length, how to fill this is a great learning.
# for 242, 24222, 24244 of these three, the biggest result must be 2424424224222 (312 order) # for 24, 2423, 2425, 24144 of these four, the biggest result must be 2425|24|2423|24144
# Complement: 242 to 24224, if it is 24, then 24242, how to see it. # make up all the numbers 0 to the same length, such as 24 complement to 24000,2423 24230, and then find the maximum number (24250) # The other numbers are based on this maximum number, such as 24 to 24242, (if you fill 6, you make up 242425) # Use a list to store key value pairs, the key is the number in num, the value is the number after the completion.
Sort the list by value size, # Output key, and get results.
Result= "" For X in range (0): i = 9-x #分别从0, 1,2,3,4,6,7,8,9 to iterate through the array at the beginning of # 0, the array at the beginning of 1 ... Listi = [] for j in Num:if str (j) [0] = = str (i): listi.append (j) If listi==[]: Continue maxLength = Len (str (max (Listi, Key=lambda C:len (
c)) #找到最大长度 # bulisti = [] for L in ListI:BuListI.append (l* (10**) after full 0 (maxlength-l En (str (l))) #如l = 15, complement 5 is 15000 Bumax=max (bulisti) #找到了补全后最大的数 tuplelist=[] # take the next
To start the complement and save it to the list as a key-value pair (tuple) for L-in Listi:bupart=str (Bumax) [0:maxlength-len (str (l)) +1] Afterbu=int (str (l) +bupart) Tuplelist.append ((L,afterbu)) Tuplelist.sort (Key=lambda c:c[1] , reverse=true) for L in Tuplelist:result=result+str (L[0]) Result=result.lstrip ("0") #如输入 [0,0], the output cannot be "the" If result== "": Return "0" #如输入 [0], can not output "" "" "
return to zero matrix
Given an MXN matrix, if an element is 0, the entire element of its row and column is changed to 0.
You need to complete the operation on the original matrix. Examples
Gives a matrix
[
[1, 2],
[0, 3]
]
Return
[
[0, 2],
[0, 0]
]
Class Solution: "" "
@param matrix:a List of lists of integers
@return: Nothing
" ""
def setzeroes ( Self, Matrix):
# Write your code here
# in a list, the horizontal and ordinate # that holds coordinates 0 is
set to 0 if matrix==[in the matrix as 0
: return
[]
Lengthy=len (Matrix)
Lengthx=len (matrix[0])
zeropositiony=[]
zeropositionx=[] for
i in Range (0,lengthy): for
J in Range (0,LENGTHX):
if matrix[i][j]==0:
zeropositiony.append (i)
Zeropositionx.append (j)
Zeropositiony=list (Set (zeropositiony))
zeropositionx=list (set (Zeropositionx) For
I in Zeropositiony: for
J in Range (0,LENGTHX):
matrix[i][j]=0 for
J in Zeropositionx:
For I in Range (0,lengthy):
matrix[i][j]=0
staggered positive numbers
Gives an array of positive and negative integers, rearranging them into a staggered array of positive and negative numbers. Attention Matters
You do not need to keep positive integers or negative integers in their original order. Examples
Give the group [-1,-2,-3, 4, 5, 6], reorder, and then change to [-1, 5,-2, 4, 3, 6] or any other answer that satisfies the requirement.
Class Solution: "" @param a:an integer array.
@return Nothing "" "Def rerange (Self, A): # To consider three cases, one is the number of positive and negative numbers are equal, one is more positive than negative, and finally a negative number more than a positive.
# separate positive and negative numbers and save to two arrays.
# for three kinds of cases, the number of positive and negative array of arrays, the pop method to continue out of the stack.
A.sort () minus=[] positive=[] for i in A:If i<0:minus.append (i) Else:positive.append (i) Lengtha=len (A) Lenminus=len (minus) Lenpositiv E=len (positive) if Lenminus = = Lenpositive:for I in range (0,lengtha,2): A[i]=min
Us[0] a[i+1]=positive[0] Minus.pop (0) positive.pop (0) If lenminus>lenpositive:count=0 a[count]=minus[0] Minus.pop (0) count+
=1 while Count<lengtha:a[count]=positive[0] Positive.pop (0) count+=1 A[count] = minus[0] Minus.pop (0) count+=1 if Lenpositive>len
Minus:count = 0 A[count] = positive[0] Positive.pop (0) Count = 1
While Count < Lengtha:a[count] = Minus[0] Minus.pop (0) Count = 1 A[count] = positive[0] Positive.pop (0) Count = 1
Longest continuous sequence
Given an unordered array of integers, find the length of the longest contiguous sequence. Description requires an O (n) sample for your algorithmic complexity
to the array [100, 4, 200, 1, 3, 2], this longest sequential sequence is [1, 2, 3, 4], and returns the desired length of 4
Class Solution: "" "
@param num, a list of integer
@return an integer
" "
def longestconsecutive ( Self, num):
#先将num里的元素去重, reorder. One traversal can be.
num = list (set (num))
maxlength=1
num.sort ()
numcurrent=num[0]
length=len (num)
count= 1 for
I in range (1,length):
if num[i]-numcurrent==1:
numcurrent=num[i]
count+=1
maxLength =max (count,maxlength)
else:
numcurrent=num[i]
count=1 return
maxLength
Random String
Gives an array of strings s and finds all of them in the sequence string (anagram). If a string is a random string, then he has the same set of letters, but the sequence of different strings is also in S. Attention Matters
All strings contain only lowercase letters
Examples
For array of strings ["Lint", "Intl", "INLT", "code"]
Back ["Lint", "INLT", "Intl"]
Class Solution:
# @param strs:a List of Strings
# @return: A List of strings
def anagrams (self, STRs):
# Sorts the strings in the STRs and places them in another array. Again, the number of occurrences of each string, if the number is greater than 1,
# Then there must be more than one sequence of random strings exist. Then Traverse STRs, find the string corresponding to the sequence of strings, put into result. Result
= []
strslist = [] for
str in STRs:
strslist.append ("". Join (sorted (str))
setstrslist = List (set (strslist)) for
i in setstrslist:
if Strslist.count (i) >1: for
str in STRs:
if Sorted ( STR) ==sorted (i):
result.append (str) return result
Swinging Sort
To give you an array that is not sorted, rearrange the original array in place to satisfy the following properties
Nums[0] <= nums[1] >= nums[2] <= nums[3] ....
Attention Matters
Please sort the array in place, that is, no extra array samples are required
Give the array of nums = [3, 5, 2, 1, 6, 4] One output scheme is [1, 6, 2, 5, 3, 4]
This sort of spaced list arrangement is a good way to first divide the list into two parts, one for the first half of the sorted list, and the second half of the sorted list, so that the interval traverses the first half and the second half to achieve the effect of the problem. One thing to be aware of is whether you want to distinguish between an odd number of lists or even numbers, if it's even okay to say that the first half is equal to the number of the second half, if it's odd, my default first half is a number more than the second half, because the first part of the list is a decimal, so the last one is definitely a decimal, So the first half has to be one more number than the second part. The code is as follows:
Class Solution (object): "" "
@param {int[]} nums a list of integer
@return Nothing, modify Nums in-place D
"" "
def wigglesort (self, nums):
nums.sort ()
Length=len (nums)
index=int ((length+1)/2)
Numsleft=nums[0:index]
numsright=nums[index:length] for
i in range (length):
If I%2==0:
nums[i]= Numsleft[0]
numsleft.pop (0)
else:
nums[i]=numsright[0]
numsright.pop (0)
print (nums)
the most kid string overlay