leetcode 156周赛(python)

Two weeks, the first time a separate written four topics, happy (of course ... not written in the examination time, mainly in the four title mapping knowledge, but also not difficult), come on!

Unique number of occurrences

To give you an array of integers  arr, please help count the number of occurrences of each number in the array.

If the number of occurrences of each number is unique, returns  true; otherwise  false.

 

Example 1:

Input: arr = [1,2,2,1,1,3] 
Output: true 
explained: In this array, one occurred three times, two occurred twice, one occurred three times. Not have the same number of occurrences of two numbers.

prompt:

  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000

See the scope of direct violence (after two weeks ... My understanding is that less than 10 ^ 10 can be solved violence)

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        d = dict()
        for i in arr:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1for key,val in d.items():
            for key2,val2 in d.items():
                if key == key2:
                    continue
                if val == val2:
                    return False
        return True

 

As far as possible so that the strings are equal

Give you the same string two lengths, s and  t.

The  s the first  i character is changed to  t the first  i character requires  |s[i] - t[i]| overhead (cost may be 0), i.e. the absolute value of the difference between two values of the ASCII characters.

The maximum budget for the change of the string is  maxCost. When converting a string, the total cost should be less than or equal to the budget, it also means that transformed string may be incomplete.

If you can  s substring in converted to its  t corresponding sub-string, the return can be transformed into a maximum length.

If  s no substring can be converted to  t the corresponding sub-string is returned  0.

 

Example:

Input: S = " ABCD " , T = " BCDF " , cost = 3 
Output: 3 
explains: S of " ABC " can become " BCD " . The cost is 3, maximum length is 3 . 

Input: S = " ABCD " , t = " CDEF " , cost =. 3 
Output: 1 
explains: a character S in any order into the corresponding t character, its overhead is 2. Therefore, the maximum length is 1.

prompt:

  • 1 <= s.length, t.length <= 10^5
  • 0 <= maxCost <= 10^6
  • s And  t only contain lowercase letters.

As said before, O (n ^ 2) ^ would be 10 to 10 times out, so for kinds of ideas, the sliding window.

# Write clumsy, sorry ha 
class Solution:
     DEF equalSubstring (Self, S: STR, T: STR, maxCost: int) -> int: 
        len_s = len (S) 
        NUM = [0 for I in Range (len_s)]
         # record the number of times 
        for I in Range (len_s): 
            NUM [I] = ABS (the ord (S [I]) - the ord (T [I]))
         # scanned initial window 
        tmp = maxCost 
        CNT = 0
         for I in Range ( len_s):
             IF tmp - NUM [I]> =0: 
                tmp - = NUM [I] 
                CNT + =. 1
             the else :
                 BREAK 
        # starts from an initial scanning window, each window delete head node, tail node added to 
        I = CNT
         the while I < len_s: 
            tmp + = NUM [ CNT-I] # deleted head node 
            tmp - = NUM [I] # added tail node 
            IF tmp> = 0: # If further expansion of 
                J = I +. 1 the while J <len_s: # expansion IF tmp - NUM [J]> = 0: 
                        tmp - =
                
                     num[j]
                        cnt += 1
                    else:
                        break
                    j += 1
                i = j
            else:
                i += 1
        return cnt

All adjacent duplicates II delete string

Give you a string  s, " k double delete duplicates" will be the  s selection  k contiguous and equal letters, and delete them so that the left and right omitted string together.

You need to  s be repeated unlimited number of times such a deletion, can not continue until so far.

After you perform all of the deletion and returns the resulting string.

The answer to this question guaranteed to be unique.

 

Example:

Input: S = " ABCD " , K = 2 
Output: " ABCD " 
Explanation: the content is not to be deleted. 

Input: S = " deeedbbcccbdaa " , K =. 3 
Output: " AA " 
explanation: 
delete " Eee " and " CCC " , to give " ddbbbdaa " 
delete " BBB " , to give " dddaa " 
Last Delete " ddd " , to give " AA "
pbbcggttciiippooaais " , K = 2 
Output: " PS "

 

prompt:

  • 1 <= s.length <= 10^5
  • 2 <= k <= 10^4
  • s It contains only lowercase letters.

The first reaction is to see the title analog stack, see 10 ^ 5 ... I am afraid of ... and then ... what to think, try holding the attitude used a list to mark each to delete an array of wheel position,

Then delete one by one (not lower than the analog complexity of the stack, I think to myself at least this does not push the stack operation), but actually had the time to post yet ... prayed with folded hands to the ~

class Solution:
     DEF RemoveDuplicates (Self, S: STR, K: int) -> STR: 
        S = List (S)
         the while True: 
            len_s = len (S)
             IF len_s < K:
                 return  '' .join (S) 
            
            I = 0 
            de = [] # index mark character array repeat 
            the while I <len (S) - k +. 1 : 
                in flag =. 1 # to find k flag is repeated characters 
                J =. 1 the while J < k:
                    
                IF S [I] = S [I +! J]: 
                        In Flag = 0
                         BREAK 
                    J + =. 1
                 IF In Flag: 
                    de.append ([I, I + J]) 
                I + = J 
                
            CNT = 0 # marked for deletion of the number of 
            for ST, ED in de: 
                S = S [: ST - cnt] + S [ED - cnt:] 
                cnt + = ED - ST
             IF  not de: # do not find a k repeating characters 
                return ''.join(s)

Minimum number of moving through the maze

Do you remember the piece of Snake rage right?

We're in a  n*n building on the grid a new maze map, the length of the snake is 2, which means that it will take up two cells. Snake (from the upper left corner (0, 0) and  (0, 1)) start to move. We  0 represent empty cells, denoted by 1 obstacle. Snake needs to be moved to the lower right corner of the maze ( (n-1, n-2) and  (n-1, n-1)).

Each move, the snake can go like this:

  • If there are no obstacles, then move right one cell. And still keep the body horizontal / vertical state.
  • If there is no obstacle, the downward movement of a cell. And still keep the body horizontal / vertical state.
  • If it is in a horizontal state and below its two units are empty, it is rotated 90 degrees clockwise. Snake from (r, c)( , (r, c+1)) to move to the (r, c)( (r+1, c), ).
  • If it is in its upright state and the right two cells are empty, it is rotated counterclockwise by 90 degrees. Snake from (r, c)( , (r+1, c)) to move to the (r, c)( (r, c+1), ).

Returns the minimum number required to move the snake arrived at the destination.

If you can not reach the destination, go back  -1.

Examples

 

 

输入:grid = [[0,0,0,0,0,1],
               [1,1,0,0,1,0],
               [0,0,0,0,1,1],
               [0,0,1,0,1,0],
               [0,1,1,0,0,0],
               [0,1,1,0,0,0]]
输出:11
解释:
一种可能的解决方案是 [右, 右, 顺时针旋转, 右, 下, 下, 下, 下, 逆时针旋转, 右, 下]。

 

这个题目看到的第一反应就是大一懵懵懂懂遇到的走迷宫了,BFS。 注意两个格子、只会右、下、旋转。

import queue

class Solution:
    def minimumMoves(self, grid: List[List[int]]) -> int:
        # 横 -- 0  竖 | 1
        n = len(grid)
        q = queue.Queue()
        vis = {} # 标记是否访问过
        #[point1, point2, 状态, 步数]
        q.put([(0,0),(0,1), False, 0])
        
        status = count = 0
        while not q.empty():
            [p1, p2, status, count] = q.get()
            if (p1,p2) in vis: # 如果访问过比较一下。
                vis[p1,p2] = min(count, vis[p1,p2])
                continue
            else:
                vis[p1, p2] = count
            if not status: # 横着的
                if p2[1] + 1 < n and grid[p2[0]][p2[1]+1] == 0: # 右移
                    q.put([p2,(p2[0],p2[1]+1), status, count+1])
                       
                if p1[0] + 1 < n and grid[p1[0]+1][p1[1]] == 0 and grid[p2[0]+1][p2[1]] == 0:
                    q.put([p1, (p1[0]+1,p1[1]), not status, count+1]) # 旋转
                    q.put([(p1[0]+1,p1[1]), (p2[0]+1,p2[1]), status, count+1]) # 下移
            else: # 竖着的
                if p2[0] + 1 < n and grid[p2[0]+1][p2[1]] == 0:
                    q.put([p2,(p2[0]+1,p2[1]), status, count+1]) # 下移
                    
                if p1[1] + 1 < n and grid[p1[0]][p1[1]+1] == 0 and grid[p2[0]][p2[1]+1] == 0: 
                    q.put([p1, (p1[0],p1[1]+1), not status, count+1]) # 旋转
                    q.put([(p1[0],p1[1]+1), (p2[0],p2[1]+1), status, count+1]) # 右移
        
        if ((n-1,n-2),(n-1,n-1)) in vis:
            return vis[(n-1,n-2),(n-1,n-1)]
        else:
            return -1

 

总结: 

  代母写的还是不够节俭,有时候思路很乱。 稍微复杂的题目脑袋瓜子在DFS的时候 回不到原点了~ 

  最后一题完全可以在规定时间内写出来,在判断是否已经访问过的时候,居然在for循环内部判断,

  想着队列里的点都是没访问过的结点,结果超时了。。(if 判断太多了。。)

 

Guess you like

Origin www.cnblogs.com/xxfna/p/11609950.html