leetcode idea briefly (61-90)

61. The rotation list

 The so-called rotation is to be disconnected disconnected place, at the right off the new head node and a tail and head the list put together.

Breakpoints may be used to find the double pointer, while count <k: p1 when the pointer reaches the k-th node (if before p1.next = None, scratch on the head), the head node P2 begins traversing two pointers together. Until p1.next == None, p2 is the breakpoint at this time, so p1.next = head, then p2.next new head node.

When looking for the node can be optimized, for example, [1,2,3], k = 50, the first time when reaching the end of the list p1, so that k = k% count, count = 0, reduced cycle times.

 

62. The different paths

① learned immediately combinatorial mathematics, this problem can be considered as m-1 th and the n-1 → ↓ number of permutations. Suppose that each of the arrows in the same direction are different individuals, then the ordering number is [(m-1) + (n-1)]!, Since the same direction of the arrow on the sequencing are equivalent, so again divided by two inside a sorting direction of the arrow number: (m-1) and (n-1)!!. That result is [(m-1) + (n-1)]! / (M-1)! (N-1) !.

② dynamic programming. Each cell of the path to the left a number of cells equal to the number of paths plus the number of a grid above the path, a first row and first column is 1 dp. Initialized two-dimensional array dp: dp = [[1] * n] + [[1] + [0] * (n-1) for _ in range (m-1)]. Iterates through all the grid floor (except the first column of the first line): dp [i] [j] = dp [i-1] [j] + dp [i] [j-1]. And finally returns dp [-1] [- 1].

    Optimize memory, do not need to save the entire dp, only the front row and the Bank can be saved. Re-optimization, you do not need to save the previous row, cur = [1] * n, layers are traversed from the start 1, after each addition the front cover line: cur [j] + = cur [j-1].

 

63. The different paths II

If obstacleGrid [i] [j] = 1, then this cell dp = 0, if this is the first cell of the first column or row, the row or column which are later dp 0. And 62 other issues the same.

 

64. minimum path and

Dynamic Programming. To each cell of the lattice and the minimum and = the smaller value + left cell of the present value of the grid. Directly in the grid array the grid present and no additional storage path space. grid [i] [j] + = min (grid [i-1] [j], grid [i] [j-1]).

 

65. significant figures

Uh. . .

 

66. plus one

Plus 1 each from the back, if greater than or equal to 10 -10, less than 10 to return, to the highest bit to carry on digits.insert (0,1). The end of the normal cycle digits.insert (0,1)

 

67. The binary sum

① bitwise addition, padded short number 0, with Carry Carry represents, a and b are added to the carry, carry is added result of the low, high as a carry, the result will be stored in the new list.

② bit operation. ^ Two numbers obtained in the result of the addition with no carry a, & Carry obtained in b. The sum of a and b, is still obtained by summing the binary result into the carry-bit loop until the carry is 0.

    The integers a and b is converted into a digital x and y, x Save Results, y carry save. ! Carry when y = 0:

        Calculate the current x and y carry-addition result: answer = x ^ y.

        Calculates the current x and y carry: carry = (x & y) << 1.

        Update x = answer, y = carry.

    Return x.

 

68. The left and right text alignment

Uh. . .

 

69. x square root

① dichotomy. Since  a is always an integer, this problem can be converted into concentration in order to find a specific integer value, a binary search may be used.

     If x <2, to return x. 2 so that the left edge of left and right margins right to x // 2. Other standard almost half.

② Newton method. Iterative formula: X K +. 1 = (X + X / X K ) / 2. x is a number x of approximation.

   x1 arbitrary initial value (greater than 0), while abs iteration is stopped when the result of change is less than the specified number (x0 - x1)> = 1: x0 = x1 record number, and then calculates x1 = (x0 + x / x0) / 2 .

③ + recursive bit operation. = 2 * √ √x (X /. 4) . << shift left by 2 is used, except for 2 >> shift right, so mySqrt (x) = mySqrt (x >> 2) << 1.

     If x is less than 2, there √ x x, returns x. left = self.mySqrt (x >> 2) << 1. right = left + 1. return left if right * right> x else right.

* Such practice can think about the relationship f (x) and f (x // 2) and the like, and then use recursion.

  Such as the first 50 questions Pow (x, n), n is an even number X n-  = X n-/ 2  * X n-/ 2  , if it is an odd number X n-  = X n-/ 2  * X n-/ 2  * X.

 

70. stairs

① dynamic programming. The method of arrival and the number of the total number of i-th order is the first order and the i-1 i 2-step method. 1 and 2 a first initialization step, starting from 3: dp [i] = dp [i-1] + dp [i-2].

② Fibonacci numbers. DP [i] is the i-th Fibonacci numbers. Each cycle: third = first + second, first = second, second = third. And dynamic programming similar point in space province.

 

71. The simplified path

① directly. Between the '/' character string extracted, placed after checking the list of words: null character skip, skip, '..' before removing an element list, a list of other characters added '.'. Finally Back '/' + '/'.join(words).

May be used instead of the dictionary if: for s in path.split ( '/'): words = { '': words, '': words, '..': words [: - 1].}. Get (s, words + [s]).

② stack. Each word push encounter '..' pop, '' do not do the operation, the final out of the stack can be.

 

72. Edit Distance

Dynamic Programming. And 44 questions about the same ideas. DP [i] [j] is equal to i before word1 word2 letters and the first j characters of edit distance (word1 [: i-1] and word [: j-1]). Three operations corresponding to the three methods to obtain dp [i] [j] in accordance with the foregoing dp:

(1) Insert: dp [i] [j] = dp [i-1] [j] + 1 (2) Delete: dp [i] [j] = dp [i] [j-1] + 1 (3 ) Alternatively: If word1 [i-1] == word [j-1] is dp [i] [j] = dp [i-1] [j-1] + 1, or dp [i] [j] = dp [i-1] [j-1]

Initializing a first row and the first column: dp [i] [0] = i and dp [0] [i] = i. Two loop through dp, the above three operations each selection a minimum number of write dp [i] [j].

 

73. Matrix Zero

If the grid is zero on the preservation of its row and column numbers, last modified. Define two row arrays and col, respectively saved as an element of the 0 row and column number. Traverse the entire matrix, if the element is 0 to row.append (i), col.append (j). Finally the row and col in the corresponding matrix elements in the row and all the columns to 0.

 

74. The two-dimensional matrix search

Two binary search, first binary comparison matrix [mid] [0] and the target, targeting row, when a conventional two points out of the row row = left - 1 (end half of the left margin is greater than the target). Then the line in the binary search target.

 

75. Color Classification

Three-way fast row, three pointer left, right, cur, again traversing the array, the current pointer cur access to the elements in the right place to go to.

初始化 left = 0,cur = 0,right = len(nums) - 1。while cur <= right:

    (1) if nums [cur] == 0, switching the nums [cur] and nums [left], left, and are added to a cur (already lined up left, left border corresponding to 0 and 1. If there is a left, left 1 will certainly change over; if there is no one left and are 0, 0 does not affect the change over of the sort).

    (2) if nums [cur] == 2, exchange nums [cur] and nums [right], cur unchanged.

    (3) if nums [cur] == 1, cur plus one.

 

76. smallest coverage substring *

 Sliding window.

left and right cursor pointer points to the first element of s. The right to the right, the expansion of the window, until the entire letter t contains a window. After obtaining a viable window, the left one by one to the right, to obtain the smallest possible window size. left and right to move somewhere if the window is no longer viable, then continue right to the right, cycle.

To determine whether it is feasible window:

    The presence of the dictionary letters t, dict_t = Counter (t), t is the number of letters will not be repeated required = len (dict_t), the presence of the dictionary window windows_counts letters = {}, the window will not be repeated the number of letters formed = 0.

    Each time the right to the left, the current alphabetic character in the windows_counts: window_counts [character] = window_counts.get (character, 0) + 1, if the character in dict_t, and added windows_counts window_counts [character] == dict_t [ character], the formed + = 1. When formed == required, it is a viable window.

    When left right, window_counts [character] - = 1, and if the character in dict_t window_counts [character] <dict_t [character], indicating less matching letters, formed - = 1. After left + = 1, the letter out of the window.

optimization:

    Establish a s_t  list, while traversing, save in the letter t s  character and the subscript . Example s_t = [(0, 'A '), (1, 'B'), (14, 'B')], using a sliding window in S_T then, the reduction of the number of characters to traverse.

 

77. The combination

Backtracking. backtrack (curr, start), a starting point and a combination of the current transmission number, if len (curr) == k is ans.append (cur) and then return, or else for i in range (start, n], i + 1). Initially com ([], 1). start usefulness is to prevent duplication.

 

78. child Collection

① back. K corresponding to the combined length is not set in the first 77 questions. backtrack (curr, start), the current combination of transmission and the subscript numbers starting point, each first ans.append (curr), then if len (curr) == k to return. Otherwise, for i in range (start, len (nums)): com (path + [nums [i]], i + 1). Initially com ([], 0).

② recursion. Initialization output = [[]]. Traversal for num in nums, the output results have been obtained in the foregoing plus the current num then placed in output: output + = [curr + [num] for curr in output].

 

79. Word Search

 Backtracking. dfs. Save the definition of two-dimensional array mark over whether to use each time the four directions using the calling function.

directs = [(0, 1), (0, -1), (1, 0), (-1, 0)] defines four running direction, each of the inspection points for direct in self.directs four directions, cur_i = i + direct [0], cur_j = j + direct [1].

 

80. Delete the sort the array duplicates II

① directly deleted. Use of such methods to remove pop, this operation time complexity  O (N) . Finally, the total complexity of  O ( N 2 ).

② cover, using the speed pointers, the pointer quickly right through the entire array, the number 2 is greater than would occur if the element nums [left] = nums [right ], left + = 1. The time complexity of O ( N ) directly delete excellent ratio.

 

81. Search rotation sorted array II

Dichotomous thinking and the same 33 questions, then that is the impact of duplicate numbers. Such as  10111, by contrast can not be determined which of the left and right half of the rotation point. Left + = 1 at this time to remove the interference.

 

82. Delete the sort the list of repeating elements II

Relatively easy to write chaos. Circulation while cur.next and cur.next.next.

If you have duplicate numbers ie cur.next.val == cur.next.next.val, the temp = cur.next, and until that number is not repeated. while (temp and temp.next and temp.val == temp.next.val): temp = temp.next. A cyclic cur.next = temp.next.

If you do not repeat it on the current element cur = cur.next.

 

83. Delete the sort the list of repeating elements

Uh. . .

 

The largest rectangle 84. Histogram *

① violence. Traversing the outer left column represents the left, the right column indicates the inner traverse right, left storage column starting current minimum, the area is calculated for each right. Time complexity of  O ( n- 2 ).

② partition. So that the current area is min_loc minimum points, the total maximum area is equal to min (maximum area min_loc comprising the maximum area min_loc left area, an area of the maximum area of the right min_loc). And the current area [i, j] is equal to the maximum area min_loc * [i-j + 1 ]. Similarly, the left and right sections, the area is also equal to the minimum required length × region within the region. Recursive solution. The average time complexity of  O ( n- log n- ), the worst O (n- 2 ).
③ center spread. From left to right the first pass, each element of the left side of the minimum recording region; a second pass from right to left, and right minimum recording each element. The third time, calculating heights [i] * (r_low [ i] - l_low [i] - 1) for each element that is the largest area for i is the i.

    Appear on both sides because if the value of i is less than the total area will be reduced, so every time a height less than the first to the left and to the right of position i a height less than the first boundary position i. Time complexity of O (n).

④ stack. The core problem is noticed and the right of the first position of seeking smaller than i left i is smaller than the first, with suitable monotonous stack processing, maintains a monotonically increasing stack. Adding Sentinel 0 about heights, traversing the end of the stack so that it is cleared.

    Through the array, if every big stack than the stack on the index. If less than the top of the stack, the stack until the stack height is greater than the current while stack and heights [st [-1]]> heights [i], calculates the area each time the stack heights [stack.pop ()] * (i - stack [-1] - 1), i is the largest area and the area between the column [-1] stack (excluding i and stack [-1]), since the minimum value of the column is just out of the stack that number.

 

85. The largest rectangle *

 ① histogram. Each block rows each successive number of "1" in row [i] = row [i-1] + 1 if row [i] == '1', for each column, can be seen as a set of directions to the left height of row [i] of the histogram, the question becomes the largest rectangular seeking these histograms, that is the question 84 of questions.

② dynamic programming. It defines three arrays of length n: left, right, height. Traversing each row, the inner row has four traverse, respectively, used to update the left, the update right, updated height, calculate the area. left [j] represents the index of the rectangle left border, right [j] represents the right border of the rectangle index, height [j] indicates the height, a rectangular area may be calculated according to the three values.

For the left [j], because the first few lines of 0 has been taken into account in the array, the only effect is 0 the current line, so the left [j] for the front row left [j] most of the left margin cur_left the current row in the the right value. If the current point is a left [j] = max (left [j], cur_left), 0 if it is left [j] = 0 and update cur_left = j + 1. right [j] Similarly, traversing from right to left. For height [j], if the point is a height [j] + = 1, 0 if height [j] = 0.

 

86. delimited list

If the traversing element is less than x, p = p.next; if greater than or equal x, put it at the beginning of the list of large (large with the other end of the current index mark, is added to the end of each time). Finally, the two connected p.next = large.next. Note initialize add dummy at the beginning, reducing evaluated.

 

87. disturb the string *

① recursion. If a period of disturbed area occurs, there must be a switching point i, the left and right so that the occurrence of disturbing i. Through each point i by one check or exchange sides without exchanging the same. Each point i, there are two cases: (1) s1 is divided into two parts at the point i, the interior of each divided portion through a plurality of switching; (2) s1 is divided into two parts in two parts and switching point i, every part of the interior division switching over several .

    Each recursion first determine whether two strings are the same, the same return True. Two strings of letters and corresponding number that appears is consistent, inconsistent returns False. Then loop through all the characters i and recursion.

    (1) 对应情况 1: if (isScramble(s1.substring[ : i+1], s2.substring[ : i+1]) && isScramble(s1.substring[i: ], s2.substring[i: ])): return true

    (2) corresponds to the case 2, two subtrees exchange: if (isScramble (s1 [i:], s2.substring [: n-i + 1]) and isScramble (s1 [i:], s2.substring [: n-i + 1]): return true

    A lot of repeated calculations can be used to optimize the memory.

② dynamic programming. DP [i] [j] [len] indicates whether the i s1 start len ​​characters can be converted to j len characters from the start of S2. Initialization dp [i] [j] [1].

     Cycle four. for len in range (1, n) examination of different lengths. for i in range (n-len + 1) and an inner layer for j in range (n-len + 1), respectively two strings traverse. for q in range (1, len + 1) traversing the cutting point.

    It is assumed that the left part of the length q, the first case can be written as dp [i] [j] [len] = dp [i] [j] [q] and dp [i + q] [j + q] [len -q], the dp [i] [j] [len] = True, break. That is the left half of the left half of the right half of the S1 and S2 and S1 and S2 of the right half.

    The second case, dp [i] [j + len-q] [q] and dp [i + q] [j] [len-q], the dp [i] [j] [len] = True, break .

    And finally returns dp [0] [0] [len], i.e., two character strings from 0 len conversion can start.

 

88. merge two ordered arrays

Double pointer back to front. loc = m + n-1 storage point nums1 m + n after the end of the number, l1 = m-1 and l2 = n-1, respectively, the end point and the end element nums1 nums2 elements. From the back, the num1 [l1] and nums2 [l2] larger value is assigned nums1 [loc], and then the larger one loc array subscript left. When l1 is less than 0, nums1 [: l2 + 1] = nums2 [: l2 + 1] and break; l2 when less than 0, break.

 

89. Gray code

Suppose it is known Golay code of order n n + 1 thus obtained can order: 0 n order before adding the binary Gray code for each element, then the Golay code sequence in reverse order n and adding 1 before each element, merging two or more collections get the n + 1-order Gray code. Because the order of those elements of the original add 1 reverse, so add the last element 0 and 1 add the first element is the same, the only difference is added at the beginning of a line with the nature of Gray code.

When the code is implemented, the outer loop of order n to 0, the inner reverse traversal previously saved results res: res.append (head + res [j]), since the maximum bit defaults to 0, so the 0 add operation may be omitted.

 

90. child Collection II

Backtracking. Still the same deduplication method.

Only once for each element, the element is provided herein a method to solve the origin, the range backtrack (start, path) and the combination of the current transfer function starting subscript numbers, numbers for each round of selection nums [start:].

For a subset of questions will not be repeated here using the current method does not overlap the element layer, if i> start and nums [i] == nums [i-1]: continue, thus avoiding occurrence in the same layer as the recursive digital duplicate.

 

Guess you like

Origin www.cnblogs.com/sumuyi/p/12531702.html