-
Notifications
You must be signed in to change notification settings - Fork 160
/
Array.md
1649 lines (1235 loc) · 47.6 KB
/
Array.md
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
<span id = "00"></span>
## 基础
- [27. Remove Element](#27-remove-element)
- [26. Remove Duplicates from Sorted Array](#26-remove-duplicates-from-sorted-array)
- [80 Remove Duplicates from Sorted Array II]
- [277 Find the Celebrity]
- [189. Rotate Array](#189-rotate-array)
- [41. First Missing Positive](#41-first-missing-positive)
- [299 Bulls and Cows]
- [134. Gas Station](#134-gas-station)
- [118. Pascal's Triangle](#118-pascals-triangle)
- [119. Pascal's Triangle II](#119-pascals-triangle-ii)
- [169. Majority Element](#169-majority-element)
- [229. Majority Element II](#229-majority-element-ii)
- [274. H-Index](#274-hindex)
- [275. H-Index II](#275-hindex-ii)
- [243 Shortest Word Distance]
- [244 Shortest Word Distance II]
- [245 Shortest Word Distance III]
- [217. Contains Duplicate](#217-contains-duplicate)
- [219. Contains Duplicate II](#219-contains-duplicate-ii)
- [220. Contains Duplicate III](#220-contains-duplicate-iii)
- [55. Jump Game](#55-jump-game)
- [45. Jump Game II](#45-jump-game-ii)
- [11. Container With Most Water](#11-container-with-most-water)
- [42. Trapping Rain Water](#42-trapping-rain-water)
- [334 Increasing Triplet Subsequence]
- [128. Longest Consecutive Sequence](#128-longest-consecutive-sequence)
- [164 Maximum Gap Bucket]
- [287. Find the Duplicate Number](#287-find-the-duplicate-number)
- [135 Candy]
- [330 Patching Array]
- [78. Subsets](#78-subsets)
- [763. Partition Labels](#763-partition-labels)
## 提高
- [4 Median of Two Sorted Arrays]
- [321 Create Maximum Number]
- [327 Count of Range Sum]
- [289. Game of Life](#289-game-of-life)
## Interval
- [57. Insert Interval](#57-insert-interval)
- [56. Merge Intervals](#56-merge-intervals)
- [986. Interval List Intersections](#986-interval-list-intersections)
- [252 Meeting Rooms]
- [253 Meeting Rooms II]
- [352 Data Stream as Disjoint Intervals]
## Counter
- [239. Sliding Window Maximum](#239-sliding-window-maximum)
- [295. Find Median from Data Stream](#295-find-median-from-data-stream)
- [325 Maximum Size Subarray Sum Equals k]
- [209. Minimum Size Subarray Sum](#209-minimum-size-subarray-sum)
- [795. Number of Subarrays with Bounded Maximum](#795-number-of-subarrays-with-bounded-maximum)
- [238. Product of Array Except Self](#238-product-of-array-except-self)
- [152. Maximum Product Subarray](#152-maximum-product-subarray)
- [228 Summary Ranges]
- [163 Missing Ranges]
## Sort
- [88. Merge Sorted Array](#88-merge-sorted-array)
- [75. Sort Colors](#75-sort-colors)
- [283. Move Zeroes](#283-move-zeroes)
- [376 Wiggle Subsequence]
- [280 Wiggle Sort]
- [324. Wiggle Sort II](#324-wiggle-sort-ii)
## 27. Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
给定一个数组nums和一个值val,就地删除该值的所有实例并返回新的长度。
不要为另一个数组分配额外的空间,必须通过使用O(1)额外的内存就地修改输入数组来做到这一点。
元素的顺序可以更改。 超出新长度后剩下的都无所谓。
**Example:1**
```
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
```
**Example:2**
```
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
```
---
### Python Solution
**分析:** 很基础的题,但是思想非常重要,是很多难的题目解法的一部分。重点在于交换元素到正确位置的规则
```python
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
pos = 0
for i in range(len(nums)):
if nums[i] != val:
nums[pos] = nums[i]
pos += 1
return pos
```
[返回目录](#00)
## 26. Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
给定一个已排序的数组nums,就地删除重复项,以使每个元素仅出现一次并返回新的长度。
不要为另一个数组分配额外的空间,必须通过使用O(1)额外的内存就地修改输入数组来做到这一点。
**Example:1**
```
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
```
**Example:2**
```
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
```
---
### Python Solution
**分析:** 和上一题近乎一样 这里用prev记录前一个的值是为了提高性能
```python
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = 0
if len(nums) == 0: return length
for i in range(1,len(nums)):
if nums[length] < nums[i]:
length += 1
nums[length] = nums[i]
return length+1
```
[返回目录](#00)
## 189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
给定一个数组,将数组向右旋转k步,其中k为非负数。
**Example:1**
```
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
```
**Example:2**
```
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
```
---
### Python Solution
**分析:** 可以用 Python 的列表的交换做,也可以通过翻转来做,推荐第二种Solution
**Solution 1:**
```python
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
k %= len(nums)
if k == 0:return
nums[:k], nums[k:] = nums[-k:], nums[:-k]
```
**Solution 2:**
```python
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
def reverse(i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
k %= len(nums)
reverse(0, len(nums) - 1)
reverse(0, k - 1)
reverse(k, len(nums) - 1)
```
[返回目录](#00)
## 41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
给定未排序的整数数组,找到最小的缺失正整数。
**Example:1**
```
Input: [3,4,-1,1]
Output: 2
```
**Example:2**
```
Input: [1,2,0]
Output: 3
```
---
### Python Solution
**分析:** Hard 难度的题目,但是思路很简单:就是把 1 到 len(nums) 的数放到对应下标(即减一)的位置,然后从头遍历,找到第一个不满足条件的值。
```python
class Solution:
def firstMissingPositive(self, nums):
for i in range(len(nums)):
while 0 <= nums[i] < len(nums) and nums[nums[i] - 1] != nums[i]:
tmp = nums[i] - 1
nums[i], nums[tmp] = nums[tmp], nums[i]
for i, v in enumerate(nums):
if v != i + 1:
return i + 1
return len(nums) + 1
```
[返回目录](#00)
## 134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
沿循环路线有N个加油站,其中加气站i处的天然气量为gas [i]。 您有一辆带无限油箱的汽车,从第i站到下一个站点(i + 1)的行车成本为[i]。 您可以从其中一个加油站的空罐开始旅程。 如果您可以沿顺时针方向绕过回路一次,则返回起始加油站的索引,否则返回-1。
**Example:1**
```
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
```
**Example:2**
```
Input:
gas = [2,3,4]
cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
```
---
### Python Solution
**分析:** 贪心算法的应用,可以理解一下。
```python
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas) < sum(cost): return -1
start = rest = 0
for i in range(len(gas)):
if gas[i] + rest < cost[i]:
start, rest = i+1, 0
else:
rest += gas[i]-cost[i]
return start
```
[返回目录](#00)
## 118. Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
给定一个非负整数numRows,生成Pascal三角形的第一个numRows。
**Example:1**
```
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
```
---
### Python Solution
**分析:** 杨辉三角,注意条件即可.
```python
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if not numRows:
return []
res = [[1]]
for i in range(1, numRows):
res += [[1] + [res[-1][i] + res[-1][i + 1] for i in range(len(res[-1]) - 1)] + [1]]
return res
```
[返回目录](#00)
## 119. Pascal's Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
给定非负索引k(其中k≤33),返回Pascal三角形的第k个索引行。
**Example:1**
```
Input: 3
Output: [1,3,3,1]
```
---
### Python Solution
**分析:** 杨辉三角的第 k 层,注意条件空间 O(k) ,所以我们要先构造好 res 。
```python
class Solution:
def getRow(self, rowIndex):
res = [1] * (rowIndex+1)
for i in range(2, rowIndex+1):
for j in range(i-1, 0, -1):
res[j] += res[j-1]
return res
```
[返回目录](#00)
## 169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
给定大小为n的数组,找到多数元素。 多数元素是出现超过n / 2倍的元素。 您可以假定数组为非空,并且多数元素始终存在于数组中。
**Example**
```
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
```
---
### Python Solution
**分析:** 摩尔投票法
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
mor, cnt = nums[0], 1
for v in nums[1:]:
if v == mor: cnt += 1
else:
cnt -= 1
if not cnt:
mor, cnt = v, 1
return mor
```
[返回目录](#00)
## 229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
给定一个大小为n的整数数组,请查找所有出现次数大于 n / 3倍的元素。
注意:该算法应在线性时间和O(1)空间中运行。
**Example**
```
Example 1:
Input: [3,2,3]
Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
```
---
### Python Solution
**分析:** 摩尔投票法进阶
```python
class Solution:
def majorityElement(self, nums):
if not nums:
return []
# 1st pass
count1, count2, candidate1, candidate2 = 0, 0, None, None
for n in nums:
if candidate1 == n:
count1 += 1
elif candidate2 == n:
count2 += 1
elif count1 == 0:
candidate1 = n
count1 += 1
elif count2 == 0:
candidate2 = n
count2 += 1
else:
count1 -= 1
count2 -= 1
# 2nd pass
result = []
for c in [candidate1, candidate2]:
if nums.count(c) > len(nums)//3:
result.append(c)
return result
```
[返回目录](#00)
## 274. H-Index
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
给定研究人员的一系列引文(每个引文是一个非负整数),编写一个函数来计算研究人员的h指数。 根据Wikipedia上h-index的定义:“如果科学家的N篇论文中的h篇每篇至少被h引用,而其他N - h篇每篇不超过h篇引用,则科学家对h索引进行索引。”
**Example:1**
```
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had
received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
```
---
### Python Solution
**分析:** 如果用排序的话,题目还是很简单的。不用快速排序的话有点类似于桶排序的思想。
```python
class Solution:
def hIndex(self, citations: List[int]) -> int:
c = sorted(citations, reverse=True)
for i, v in enumerate(c):
if v <= i:
return i
return len(c)
```
**用二分法优化** 注意 hi 的取值,这样可以在所有都大于的情况取到正确的值。
```python
class Solution:
def hIndex(self, citations: List[int]) -> int:
c = sorted(citations, reverse=True)
lo, hi = 0, len(c)
while lo < hi:
mid = (lo + hi) // 2
if c[mid] > mid:
lo = mid + 1
else:
hi = mid
return lo
```
**O(n)时间和空间**
```python
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
citeCount = [0] * (n+1)
for c in citations:
if c >= n:
citeCount[n] += 1
else:
citeCount[c] += 1
i = n-1
while i >= 0:
citeCount[i] += citeCount[i+1]
if citeCount[i+1] >= i+1:
return i+1
i -= 1
return 0
```
[返回目录](#00)
## 275. H-Index II
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
给定一组以研究者的升序排列的引用(每个引用是一个非负整数),编写一个函数来计算研究者的h指数。 根据Wikipedia上h-index的定义:“如果h他/她的N篇论文中至少有h篇引用,则科学家对h进行索引,而其他n-h篇论文中的h篇引用均不超过h篇。”
**Example:1**
```
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
```
---
### Python Solution
**分析:** 延续上一道题,如果已经排好序,直接用二分法就可以了。
```python
class Solution:
def hIndex(self, citations: List[int]) -> int:
lo, hi = 0, len(citations)
while lo < hi:
mid = (lo + hi) // 2
if citations[~mid] > mid:
lo = mid + 1
else:
hi = mid
return lo
```
[返回目录](#00)
## 217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
给定一个整数数组,查找数组是否包含任何重复项。 如果数组中任何值至少出现两次,则函数应返回true,如果每个元素都不相同,则返回false。
**Example:1**
```
Input: [1,2,3,1]
Output: true
```
**Example:2**
```
Input: [1,2,3,4]
Output: false
```
---
### Python Solution
**分析:** 用 set 作 hash 表,如果存在重复的元素,则 set 的长度一定小于 nums 的长度。
```python
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) > len(set(nums))
```
[返回目录](#00)
## 219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
给定一个整数数组和一个整数k,找出数组中是否存在两个不同的索引i和j,使得nums [i] = nums [j]并且i和j之间的绝对差值最多为k。
**Example:1**
```
Input: nums = [1,2,3,1], k = 3
Output: true
```
**Example:2**
```
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
```
---
### Python Solution
**分析:** 建立哈希表,存储距离最近的上一次索引,判断距离,如果满足条件了将 flag 设为 True ,否则不满足返回 flag = Flase 。
```python
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
used = {}
flag = False
for i, v in enumerate(nums):
if v in used and not flag:
flag = (i - used[v] <= k)
used[v] = i
return flag
```
[返回目录](#00)
## 220. Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
给定一个整数数组,请找出数组中是否存在两个不同的索引i和j,以使 nums[i] 和 nums[j] 之间的绝对差最大为 t,并且i和j之间的绝对差最大为 k
**Example:1**
```
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
```
**Example:2**
```
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
```
---
### Python Solution
**分析:** 暴力法加了个判断效率还奇高?
```python
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t == 0 and len(nums) == len(set(nums)): return False
for i in range(len(nums)):
for j in range(1, k + 1):
if i + j >= len(nums): break
if abs(nums[i] - nums[i + j]) <= t: return True
return False
```
[返回目录](#00)
## 55. Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
给定一个非负整数数组,您最初位于该数组的第一个索引处。 数组中的每个元素代表您在该位置的最大跳转长度。 确定您是否能够达到最后一个索引。
**Example:1**
```
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
```
**Example:2**
```
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
```
---
### Python Solution
**分析:** 从后往前或者从前往后。从前往后,看当前位置能不能到达,并更新最远位置。
```python
class Solution: # 从后往前,不能优化。
def canJump(self, nums: List[int]) -> bool:
lastpos = len(nums)-1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= lastpos:
lastpos = i
return lastpos == 0
```
```python
class Solution: # 从前往后,看当前位置能不能到达,并更新最远位置。
def canJump(self, nums: List[int]) -> bool:
farest = 0
for i, v in enumerate(nums):
if i > farest:
return False
farest = max(farest, i + v)
return True
```
[返回目录](#00)
## 45. Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
给定一个非负整数数组,您最初位于该数组的第一个索引处。 数组中的每个元素代表您在该位置的最大跳转长度。 您的目标是在最少的跳数中达到最后的索引。
**Example:1**
```
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
```
---
### Python Solution
**分析:** 虽然难度是 hard 但其实很简单。而且题目里说保证可以到达,约束条件就更少了。
```python
class Solution:
def jump(self, nums: List[int]) -> int:
tmp = [i + v for i, v in enumerate(nums)]
left = right = res = 0
while right < len(nums)-1:
left, right = right, max(tmp[left:right+1])
res += 1
return res
```
[返回目录](#00)
## 11. Container With Most Water
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
给定n个非负整数a1,a2,...,an,其中每个代表坐标(i,ai)上的点。 绘制n条垂直线,使线i的两个端点位于(i,ai)和(i,0)。 找到两条线,它们与x轴一起形成一个容器,以便该容器包含最多的水。
**Example:1**
```
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
```
---
### Python Solution
**分析:** 简化版的42题
```python
class Solution:
def maxArea(self, height: List[int]) -> int:
res, i, j = 0, 0, len(height) - 1
while i < j:
res = max(res, min(height[i], height[j]) * (j - i))
if height[i] > height[j]: j -= 1
else: i += 1
return res
```
[返回目录](#00)
## 42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
给定n个代表海拔图的非负整数,其中每个条的宽度为1,计算下雨后它能捕获多少水。
**Example:1**
```
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
```
---
### Python Solution
**分析:** 双指针做法,左右贪心。
```python
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
res, i, j = 0, 0, len(height)-1
l_max, r_max = height[i], height[j]
while i < j:
if l_max > r_max:
j -= 1
r_max = max(r_max, height[j])
res += max(0, r_max - height[j])
else:
i += 1
l_max = max(l_max, height[i])
res += max(0, l_max - height[i])
return res
```
[返回目录](#00)
## 128. Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
给定一个未排序的整数数组,请找出最长的连续元素序列的长度。 您的算法应以O(n)复杂度运行。
**Example:1**
```
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
```
---
### Python Solution
**分析:** 利用 hashset 来排除重复元素,然后在里面一个一个找,当然 for 循环里第一个条件就是优化重复计算的。
```python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
best = max(best, y - x)
return best
```
[返回目录](#00)
## 287. Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
给定一个包含n + 1个整数的数组,其中每个整数在1到n(包括1和n)之间,请证明必须存在至少一个重复的数字。 假定只有一个重复的数字,找到重复的一个。
**Example**
```
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
```
---
### Python Solution
**分析:** 弗洛伊德判断环的方法
```python
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
f = s = 0
while not f or f != s:
f = nums[nums[f]]
s = nums[s]
f = 0
while f != s:
f = nums[f]
s = nums[s]
return s
```
[返回目录](#00)
## 78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
给定一组不同的整数nums,返回所有可能的子集(幂集)。 注意:解决方案集不得包含重复的子集。
**Example:1**
```
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
```
---
### Python Solution
**分析:**
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
subsets = [[]]
for n in nums:
subsets += [s + [n] for s in subsets]