def solution(X, A): positions = set() for i in range(len(A)): if A[i] not in positions: positions.add(A[i]) if len(positions) == X: return i return -1
def solution(A): dict_set = set(x + 1 for x in range(len(A))) for a in A: if a in dict_set: dict_set.remove(a) else: return 0 if not dict_set: # set is empty return 1 return 0
def solution(A): s = set() while A: s.add(A.pop()) for i in range(1, len(s) + 2): if i not in s: return i return 1
這個題必需要說一下,按照正常思路提交後performance徹底失敗。根據testcase提示得知是max方法出的問題。數組
本身分析發現每一次max操做至關於重置全部數字,而後中途的重置沒有實際意義,最後一次重置纔是有價值的。google
然而仍是沒有想到一個好的方式,後面google別人的代碼才發現increase方法須要及時更新最後一次重置的值。spa
這個思路在於每一次重置時不實際操做數組A,因此複雜度是O(1),只要最後作一次真實重置,達到O(M+N)code
class Counters(object): def __init__(self, n): self.counter_list = [0] * n self.max_counter = 0 self.last_max_value = 0 self.size = n def increase(self, x): x -= 1 # 0-start-index if self.counter_list[x] < self.last_max_value: # reset after last_max_update self.counter_list[x] = self.last_max_value self.counter_list[x] += 1 if self.counter_list[x] > self.max_counter: self.max_counter = self.counter_list[x] def max(self): # cache last max update value self.last_max_value = self.max_counter def current_list(self): for i in range(self.size): if self.counter_list[i] < self.last_max_value: # position not updated self.counter_list[i] = self.last_max_value return self.counter_list def solution(N, A): counters = Counters(N) for a in A: if a == N + 1: counters.max() else: counters.increase(a) return counters.current_list()