-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode.py
4900 lines (3918 loc) · 109 KB
/
leetcode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: d:\CodeWareHouse\leetcode.py
# Project: d:\CodeWareHouse
# Created Date: Wednesday, February 7th 2018, 4:01:41 pm
# Author: guchenghao
# -----
# Last Modified: guchenghao
# Modified By: Monday, 19th March 2018 3:32:41 pm
# -----
# Copyright (c) 2018 University
# Fighting!!!
# All shall be well and all shall be well and all manner of things shall be well.
# We're doomed!
###
'''[Tips]
# ! 双指针法(Two-Pointer)经常用在sorted的list中
'''
# %%
# * two sum
# ! 如果使用冒泡排序的方法,会超时
import numpy as np
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
number = nums[i]
nums_1 = nums[i + 1:]
nums_1 = np.array(nums_1)
sum_ = nums_1 + number
p = (sum_ == target)
if 1 in p:
p = list(p)
idx = p.index(True)
return [i, i + idx + 1]
else:
continue
def twoSum(self, nums, target):
# ! 这个方法比较耗时
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
diff = target - nums[i]
temp = nums[i + 1:]
if diff in temp:
return [i, temp.index(diff) + i + 1]
# %%
# * Remove Element
def removeElement(nums, val):
# ! two-pointer 方法
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
j = 0
for i in range(len(nums)):
if nums[i] == val:
continue
else:
nums[j] = nums[i]
j = j + 1
return j
# %%
# * Search Insert Position
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if target < nums[i]:
return i
if target > nums[i]:
if i == len(nums) - 1:
return i + 1
continue
# %%
# * Missing Number
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(len(nums)):
if nums[0] != 0:
return 0
if nums[-1] != len(nums):
return len(nums)
if nums[i+1] - nums[i] == 1:
continue
else:
return nums[i] + 1
# %%
# * Remove Duplicates from Sorted List
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
seen = [head.val]
prev_node = dum = head
node = head.next
while node is not None:
if node.val in seen:
# delete it
prev_node.next = node.next
node = node.next
else:
seen.append(node.val)
prev_node = node
node = node.next
return dum
# %%
# * Length of Last Word
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
strArr = s.strip(' ').split(' ')
return len(strArr[len(strArr) - 1])
# %%
# * Path Sum
# * 使用了递归的方式,遍历树
# ! Top-Down的方法
'''
1. return specific value for null node
2. update the answer if needed // anwer <-- params
3. left_ans = top_down(root.left, left_params) // left_params <-- root.val, params
4. right_ans = top_down(root.right, right_params) // right_params <-- root.val, params
5. return the answer if needed // answer <-- left_ans, right_ans
'''
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if sum - root.val == 0 and root.left is None and root.right is None:
return True
else:
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
# %%
# * Contains Duplicate
def containsDuplicate(self, nums):
# ! 不知道为什么之前会想这么复杂。。。。。
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
if len(nums) == 1:
return False
for i in range(len(nums)):
if i == len(nums) - 1:
break
if nums[i] == nums[i + 1]:
return True
else:
continue
return False
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return False if len(nums) == len(set(nums)) else True
# %%
# * Contains Duplicate II
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dic = {}
for i, v in enumerate(nums):
if v in dic and i - dic[v] <= k:
return True
dic[v] = i
return False
# %%
# * Best Time to Buy and Sell Stock
# def maxProfit(self, prices): # ! 超时
# """
# :type prices: List[int]
# :rtype: int
# """
# result = []
# for i in range(len(prices)):
# if i == len(prices) - 1:
# break
# num_1 = prices[i + 1:]
# if max(num_1) - prices[i] <= 0:
# continue
# else:
# result.append(max(num_1) - prices[i])
# if result == []:
# return 0
# else:
# return max(result)
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n <= 1:
return 0
max_profit = 0
low_price = prices[0]
for i in range(1, n):
low_price = min(low_price, prices[i])
max_profit = max(max_profit, prices[i]-low_price)
return max_profit
# %%
# * Majority Element
import math
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num_dict = {}
n = len(nums)
if n == 1:
return nums[0]
for idn, v in enumerate(nums):
if v in num_dict:
num_dict[v] = num_dict[v] + 1
else:
num_dict[v] = 1
result = max(num_dict.values())
if result >= math.floor(n / 2):
return max(num_dict, key=num_dict.get)
# %%
# * Find All Numbers Disappeared in an Array
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1, len(nums)+1)) - set(nums))
# %%
# * Reshape the Matrix
import numpy as np
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
try:
return np.reshape(nums, (r, c)).tolist()
except:
return nums
# %%
# * Largest Number At Least Twice of Others
import copy
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
copy_nums = copy.deepcopy(nums)
nums.sort()
maximum = nums[-1]
for i in range(len(nums) - 1):
if nums[i] == maximum:
return -1
else:
if maximum >= nums[i] * 2:
continue
else:
return -1
return copy_nums.index(maximum)
# %%
# * Move Zeroes
def moveZeroes(self, nums): # ! 这个方法慢
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero_num = nums.count(0)
for i in range(zero_num):
nums.remove(0)
nums.append(0)
def moveZeroes(self, nums): # ! 这个方法快100ms
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if length <= 1:
return
zero_count = 0
i = 0
while i < length:
if nums[i] == 0:
zero_count += 1
else:
nums[i - zero_count] = nums[i]
i += 1
j = 1
while j <= zero_count:
nums[length - j] = 0
j += 1
# %%
# * Two Sum II - Input array is sorted
import numpy as np
def twoSum(self, numbers, target): # ! 方法可行,但超时了
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
for idn, v in enumerate(numbers):
number_1 = np.array(numbers[idn + 1:])
result = number_1 + v
p = (result == target)
if 1 in p:
p = list(p)
idn_2 = p.index(True)
return [idn + 1, idn_2 + idn + 2]
def twoSum(self, numbers, target): # ! 这个方法可行
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
numbers_dict = {}
for idn, v in enumerate(numbers):
if target - v in numbers_dict:
return [numbers_dict[target - v] + 1, idn + 1]
numbers_dict[v] = idn
def twoSum(self, numbers, target): # ! two-pointer
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i = 0
j = len(numbers) - 1
res = []
while True:
addition = numbers[i] + numbers[j]
if addition == target:
res.append(i + 1)
res.append(j + 1)
break
elif addition > target:
j -= 1
else:
i += 1
return res
# %%
# * Max Consecutive Ones
from collections import defaultdict
def findMaxConsecutiveOnes(self, nums):
# ! 利用dict来存储不同区段的'1'的个数
"""
:type nums: List[int]
:rtype: int
"""
nums_dict = defaultdict(int)
i = 0
for num in nums:
if num == 1:
nums_dict[i] = nums_dict[i] + 1
else:
i = i + 1 # ! 如果当前的字符不是'1'而是'0'是,通过加1来更新key
if nums_dict.values():
return max(nums_dict.values())
else:
return 0
# %%
# * Maximum Product of Three Numbers
from functools import reduce
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return max(nums[1] * nums[0] * nums[-1], reduce(lambda x, y: x * y, nums[-3:]))
# %%
# * Longest Continuous Increasing Subsequence
from collections import defaultdict
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_dict = defaultdict(int)
count = 1
i = 0
if nums == []:
return 0
for idn in range(len(nums) - 1):
if nums[idn + 1] > nums[idn]:
count = count + 1
nums_dict[i] = count
else:
i = i + 1
count = 1
if nums_dict.values():
return max(nums_dict.values())
else:
return 1
# %%
# * Find Pivot Index
from functools import reduce
def pivotIndex(self, nums): # ! 超时了
"""
:type nums: List[int]
:rtype: int
"""
for idn, num in enumerate(nums):
if idn == 0:
if reduce(lambda x, y: x + y, nums[idn + 1:]) == 0:
return idn
else:
continue
if idn == len(nums) - 1:
if reduce(lambda x, y: x + y, nums[:idn]) == 0:
return idn
else:
break
if reduce(lambda x, y: x + y, nums[idn + 1:]) == reduce(lambda x, y: x + y, nums[:idn]):
return idn
return -1
def pivotIndex(self, nums): # ! 143ms
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = sum(nums)
for idn, num in enumerate(nums):
right -= num
if right == left:
return idn
left += num
return -1
def pivotIndex(self, nums): # ! 11764 ms, 这个运行时间,我枯了
"""
:type nums: List[int]
:rtype: int
"""
for idx in range(len(nums)):
if sum(nums[:idx]) == sum(nums[idx + 1:]):
return idx
return -1
# %%
# * Plus One
def plusOne(self, digits): # ! 68ms
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 0
for item in digits:
num = num * 10 + item
return [int(i) for i in str(num+1)]
# %%
# * Pascal's Triangle
def generate(self, numRows): # ! 最直接的方式,双重循环, O(n^2)
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
result = []
temp = [0, 1]
for i in range(numRows):
row = []
for j in range(len(temp) - 1):
row.append(temp[j] + temp[j+1])
result.append(row)
temp = row[:]
temp.insert(0, 0)
temp.append(0)
return result
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
:example:
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1
"""
if numRows == 0:
return []
res = [[1]]
# ! "+" 在这里表示数组的拼接
for _ in range(1, numRows):
res += [list(map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1]))]
return res
# %%
# * Pascal's Triangle II
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [[1]]
for _ in range(1, rowIndex + 1):
res += [list(map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1]))]
return res[rowIndex]
def getRow(self, rowIndex): # ! 改良版,更快, 63ms
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [1]
for _ in range(1, rowIndex + 1):
res = list(map(lambda x, y: x+y, res + [0], [0] + res))
return res
def getRow(self, rowIndex): # ! 更快 55ms
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [1]
for _ in range(1, rowIndex + 1):
res = [x + y for x, y in zip([0]+res, res+[0])]
return res
# %%
# * Maximum Average Subarray I
def findMaxAverage(self, nums, k): # ! 超时
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
maxSum = -10001
curSum = 0
for i in range(len(nums) - k + 1):
curSum = sum(nums[i:i + k])
maxSum = max(maxSum, curSum)
return float(maxSum / k)
def findMaxAverage(self, nums, k): # ! 212ms
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
sums = [0] + list(itertools.accumulate(nums))
# ! sub: sums[k:] 和 sums对应位置相减,不对应的位置舍弃
return max(map(operator.sub, sums[k:], sums)) / k
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
begin = 0
end = 0
n = len(nums)
kavg = 0
if k < len(nums):
ksum = sum(nums[0:k]) # sum of first k items
kavg = ksum / float(k) # avg of first k items
beg = 0 # beginning of avg window
x = k # end of avg window
while x < n: # when end falls beyond n
ksum = ksum - nums[beg] + nums[x] # get ksum
# set kavg to maximum of kavg and new kavg
kavg = max(kavg, (ksum / float(k)))
beg += 1 # begining of avg window increases
x += 1 # end of avg window increases
else:
# kavg if items are lesser than k
kavg = sum(nums) / float(len(nums))
return kavg
# %%
# * Can Place Flowers
def canPlaceFlowers(self, flowerbed, n): # ! 118ms
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 0
w = len(flowerbed) - 1
for idn, v in enumerate(flowerbed):
if count >= n:
return True
if v == 0 and idn == 0:
if idn == w:
count += 1
break
if flowerbed[idn + 1] != 1:
count += 1
flowerbed[idn] = 1
continue
continue
if v == 0 and idn == w:
if flowerbed[idn - 1] != 1:
count += 1
break
break
if v == 0 and flowerbed[idn + 1] != 1 and flowerbed[idn - 1] != 1:
flowerbed[idn] = 1
count += 1
return count >= n
# %%
# * Third Maximum Number
def thirdMax(self, nums): # ! 64ms
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
num_set = list(set(nums))
num_set.sort()
if len(num_set) < 3:
return num_set[-1]
return num_set[-3]
# %%
# * Rotate Array
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
# ! 如果 k > 数组的长度,则取数组长度的余数作为k,例如: len = 7,k=3和k=10的结果一样
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]
# %%
# * Shortest Unsorted Continuous Subarray
def findUnsortedSubarray(self, nums): # ! 104ms
"""
:type nums: List[int]
:rtype: int
"""
# ! 列表推导式
res = [i for (i, (a, b)) in enumerate(
zip(nums, sorted(nums))) if a != b]
return 0 if not res else res[-1]-res[0]+1
# %%
# * Find All Duplicates in an Array
def findDuplicates(self, nums): # ! 这种方式运行时间 322ms
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort()
result = []
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]:
result.append(nums[i])
return result
def findDuplicates(self, nums): # ! 这种方式运行时间长 359ms
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort()
result = []
i = 0
while i < len(nums) - 1:
if nums[i] == nums[i + 1]:
result.append(nums[i])
i = i + 2
else:
i = i + 1
return result
# %%
# * Teemo Attacking
def findPoisonedDuration(self, timeSeries, duration): # ! 138ms
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
result = duration
if timeSeries == []:
return 0
for i in range(len(timeSeries) - 1):
if timeSeries[i + 1] > (timeSeries[i] + duration):
result += duration
continue
else:
result += (timeSeries[i + 1] - timeSeries[i])
return result
# %%
# * Product of Array Except Self
def productExceptSelf(self, nums): # ! 167ms
"""
:type nums: List[int]
:rtype: List[int]
"""
p = 1
n = len(nums)
output = []
# ! [1,1,2,6]
for i in range(0, n):
output.append(p)
p = p * nums[i]
p = 1
# ! [24,12,4,1]
for i in range(n-1, -1, -1):
output[i] = output[i] * p
p = p * nums[i]
return output # ! [24,12,8,6]
# %%
# * Subsets
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [[]]
for num in nums:
res += [item+[num] for item in res]
return res
# %%
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
return sum(map(J.count, S)) # ! map函数的用法
# return sum(s in J for s in S)
# %%
# * Keyboard Row
import re
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
return list(filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words))
# %%
# * Distribute Candies
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
number_sister = len(candies) / 2
candies_set = set(candies)
if len(candies_set) <= number_sister:
return len(candies_set)
else:
return int(number_sister)
# %%
# * Island Perimeter
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
result = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] is 1:
result += 4
if j > 0 and grid[i][j-1] is 1:
result -= 2
if i > 0 and grid[i-1][j] is 1:
result -= 2
return result
# %%
# * Single Number
def singleNumber(self, nums): # ! 93ms
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
i = 0
if len(nums) == 1:
return nums[0]
while i <= len(nums) - 1:
if i == len(nums) - 1:
return nums[i]
if nums[i] == nums[i + 1]:
i = i + 2
continue
else:
return nums[i]
import operator
def singleNumber(self, nums): # ! 68ms
"""
:type nums: List[int]
:rtype: int
"""
# ! 使用异或运算,比较巧妙
res = 0
for num in nums:
res ^= num
return res
# %%
# * Find the Difference
def findTheDifference(self, s, t): # ! 118ms 遍历字符串
"""
:type s: str
:type t: str
:rtype: str
"""
return [item for item in t if item not in s or s.count(item) != t.count(item)][0]
import operator
from functools import reduce