-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlintcode.py
4592 lines (4283 loc) · 137 KB
/
lintcode.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
# -*- coding: utf-8 -*-
###########################################
# Add Two Numbers
# You have two numbers represented by a linked list, where each node contains
# a single digit. The digits are stored in reverse order, such that the 1's digit is
# at the head of the list. Write a function that adds the two numbers and
# returns the sum as a linked list.
# Example
# Given 7->1->6 + 5->9->2. That is, 617 + 295.
# Return 2->1->9. That is 912.
# Given 3->1->5 and 5->9->2, return 8->0->8.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import math
from functools import reduce
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def listGenerator(l):
if (len(l) == 0):
return None
prev = head = ListNode(None)
for value in l:
prev.next = ListNode(value)
if (head.val == None):
head = prev.next
prev = prev.next
return head
def listPrint(head):
print('print list nodes')
while not (head == None):
print('%d --> ' % head.val)
head = head.next
def listPrint(self):
head = self
print('print list nodes')
while not (head == None):
print('%d --> ' % head.val)
head = head.next
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def treeGenerator(l):
ret = list()
i = 0
while (i < len(l)):
ret.append(TreeNode(l[i]))
i += 1
# map(lambda x : ret.append(TreeNode(x)), l)
return ret
def treePrintNodes(self):
ret = "%d -> " % self.val
if (self.left != None):
ret += self.left.treePrintNodes()
if (self.right != None):
ret += self.right.treePrintNodes()
return ret
def treePrint(self):
print('print tree nodes: ', self.treePrintNodes())
class SolutionAddTwoNumbers:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
increment = 0
prev = head = ListNode(None)
while True:
if (l1 == None and l2 == None):
break
v1 = v2 = 0
if (l1 != None):
v1 = l1.val
if (l2 != None):
v2 = l2.val
value = v1 + v2 + increment
increment = value // 10
value = value % 10
# construct new node
prev.next = ListNode(value)
if head.val == None:
head = prev.next
prev = prev.next
# next loop
if (l1 != None):
l1 = l1.next
if (l2 != None):
l2 = l2.next
# end of loop
if increment == 1: # add one more node
prev.next = ListNode(increment)
return head
# end of SolutionTwoSum
# Two sum
# Given an array of integers, find two numbers such that they add up to a specific target number.
# The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.
# Notice
# You may assume that each input would have exactly one solution
# Example
# numbers=[2, 7, 11, 15], target=9
# return [1, 2]
# solution: search from diagonal line
# x x x x x x x x
# x x x x x x x
# x x x x x x
# x x x x x
# x x x x
# x x x
# x x
# x
class SolutionTwoSum:
"""
@param numbers : An array of Integer
@param target : target = numbers[index1] + numbers[index2]
@return : [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, numbers, target):
# write your code here
if (len(numbers) <= 1):
return None
i = 0
j = len(numbers) - 1
s = sorted(numbers) # s --> sorted_numbers
while True:
sum = s[i] + s[j]
if (sum == target):
# return result
index1 = numbers.index(s[i]) + 1
index2 = numbers.index(s[j]) + 1
# search from after index1, there may be same number
while True:
if (index2 == index1):
index2 = numbers.index(s[j], index2) + 1
else:
break
if (index1 < index2):
return list([index1, index2])
else:
return list([index2, index1])
if (target > sum):
# search in next triangles
i += 1
else:
j -= 1
if (i >= j):
# end, not found
return None
return None
# class SolutionTwoSum:
# def __init__(self):
# self.tempArray = []
# self.sorted_numbers = []
# self.startIndex = 0
#
# def storeTempArray(self, index):
# print(index)
# self.tempArray.append(
# [self.sorted_numbers[self.startIndex] + self.sorted_numbers[index]])
# return
# """
# @param numbers : An array of Integer
# @param target : target = numbers[index1] + numbers[index2]
# @return : [index1 + 1, index2 + 1] (index1 < index2)
# """
# def twoSum(self, numbers, target):
# # write your code here
# i = 0
# j = 0
# index = 0
# self.sorted_numbers = sorted(numbers)
# while (index < len(numbers)):
# startIndex = index
# r = map(self.storeTempArray, range(index, len(numbers)))
# print(list(r))
# index += 1
# print(self.tempArray)
# return
#
# end of SolutionTwoSum
# Single Number
# Given 2*n + 1 numbers, every numbers occurs twice except one, find it.
class SolutionSingleNumber:
def singleNumber(self, A):
if (len(A) == 0):
return 0
return reduce(lambda x, y: x ^ y, A)
# Single Number II
# Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
# Example
# Given [1,1,2,3,3,3,2,2,4,1] return 4
class SolutionSingleNumberII:
"""
@param A : An integer array
@return : An integer
"""
def singleNumberII(self, A):
# write your code here
if (len(A) == 0):
return 0
if (len(A) == 1):
return A[0]
bits = list(0 for x in range(32)) # 32 bits
i = 0
while (i < len(A)):
num = A[i]
j = 0
while (num > 0):
bits[j] += num & 1
num >>= 1
j += 1
i += 1
# find bits of 1 after mod 3
i = 0
while (i < len(bits)):
bits[i] %= 3
i += 1
# find result number
result = 0
bitValue = 1
i = 0
while (i < len(bits)):
result += bits[i] * bitValue
bitValue *= 2
i += 1
return result
# bool flags for characters
class CharBoolFlags:
flags = list(-1 for x in range(256))
@staticmethod
def reset():
CharBoolFlags.flags = list(-1 for x in range(256))
return
@staticmethod
def get(ch):
return CharBoolFlags.flags[ord(ch)]
@staticmethod
def set(ch, v):
CharBoolFlags.flags[ord(ch)] = v
return
# Longest Substring Without Repeating Characters
# Given a string, find the length of the longest substring without repeating characters.
class SolutionLongestSubstring:
# @param s: a string
# @return: an integer
def lengthOfLongestSubstring(self, s):
# write your code here
longest = 0
currentLen = 0
CharBoolFlags.reset()
currentStart = current = 0
while current < len(s):
ch = s[current]
flagPos = CharBoolFlags.get(ch)
if (flagPos == -1):
currentLen += 1
else: # ch already appeared
if (currentStart <= flagPos and flagPos < current):
# found: repeating char
if (longest < currentLen):
longest = currentLen
# move start to next of repeating char
# currentLen is not changed
currentStart = flagPos + 1
currentLen = current - currentStart + 1
else:
# not found: char appeared in previous string
currentLen += 1
# must update flag-pos as current
CharBoolFlags.set(ch, current)
# next char
current += 1
# last sub-string is longest
if (longest < currentLen):
longest = currentLen
return longest
# end of SolutionLongestSubstring
# Implement a stack with min() function,
# which will return the smallest number in the stack.
# It should support push, pop and min operation all in O(1) cost.
# Notice
# min operation will never be called if there is no number in the stack.
# sulution: 1 4 2 8 5 6
# 1 --> 2 --> 5 --> 6
class MinStack(object):
def __init__(self):
# do some intialize if necessary
self.stack = []
self.minValue = [] # store min numbers
def push(self, number):
# write yout code here
self.stack.append(number)
if (len(self.minValue) == 0):
self.minValue.append(number)
else:
if (number <= self.minValue[-1]):
# NOTE: there may be same min values
self.minValue.append(number)
def pop(self):
# pop and return the top item in stack
if (len(self.stack) == 0):
return None
else:
number = self.stack.pop()
if (number == self.minValue[-1]):
self.minValue.pop()
return number
def min(self):
# return the minimum number in stack
if (len(self.minValue) == 0):
return None
return self.minValue[-1]
# Reverse Integer
# Reverse digits of an integer. Returns 0 when the reversed integer overflows
# (signed 32-bit integer).
class SolutionReverseInteger:
min32Bit = -1 * (pow(2, 31) - 1)
max32Bit = pow(2, 31)
# @param {int} n the integer to be reversed
# @return {int} the reversed integer
def reverseInteger(self, n):
# Write your code here
isNeg = n < 0
n = abs(n)
r = 0
while True:
lastDigit = n % 10
n = n // 10
r = r * 10 + lastDigit
if (n == 0):
if (isNeg):
r *= -1
# check overflow
if (SolutionReverseInteger.min32Bit > r or
r > SolutionReverseInteger.max32Bit):
r = 0
return r
# end of class SolutionReverseInteger:
# Given a list of numbers, return all possible permutations.
# Notice
# You can assume that there is no duplicate numbers in the list.
# Example
# For
# nums = [1, 2, 3], the
# permutations
# are:
# [
# [1, 2, 3],
# [1, 3, 2],
# [2, 1, 3],
# [2, 3, 1],
# [3, 1, 2],
# [3, 2, 1]
# ]
#
#
class SolutionPermutation:
"""
@param nums: A list of Integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
results = []
if (len(nums) == 0):
results.append([])
return results
nums = sorted(nums)
results.append(list(nums))
if (len(nums) == 1):
return results
i = len(nums) - 1
while (True):
if (i == 0):
break
if (nums[i - 1] < nums[i]):
# find in [index, len), a min number > nums[index - 1]
j = len(nums) - 1
while (nums[j] < nums[i - 1]):
j -= 1
temp = nums[i - 1]
nums[i - 1] = nums[j]
nums[j] = temp
# asc sort [index, len), currently must be desc
# simply swap to do sorting
start = i
end = len(nums) - 1
while (start < end):
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
results.append(list(nums))
# print(list(nums))
i = len(nums) - 1 # reset index
else:
i -= 1
return results
# Permutation Sequence
# Given n and k, return the k-th permutation sequence.
# Notice
# n will be between 1 and 9 inclusive.
# Example
# For n = 3, all permutations are listed as follows:
# "123"
# "132"
# "213"
# "231"
# "312"
# "321"
# If k = 4, the fourth permutation is "231"
class SolutionPermutationSequence:
def getString(self, n):
ret = ''
i = 0
while (i < len(n)):
ret += ('%d' % n[i])
i += 1
return ret
"""
@param n: n
@param k: the k-th permutation
@return: a string, the k-th permutation
"""
def getPermutation(self, n, k):
# write your code here
nums = [i + 1 for i in range(n)]
if (len(nums) == 0):
return ""
nums = sorted(nums)
if (k == 1):
return self.getString(nums)
counter = 1
i = len(nums) - 1
while (True):
if (i == 0):
break
if (nums[i - 1] < nums[i]):
# find in [index, len), a min mumber > nums[index - 1]
j = len(nums) - 1
while (nums[j] < nums[i - 1]):
j -= 1
temp = nums[i - 1]
nums[i - 1] = nums[j]
nums[j] = temp
# asc sort [index, len), currently must be desc
# simply swap to do sorting
start = i
end = len(nums) - 1
while (start < end):
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
counter += 1
if (counter == k):
return self.getString(nums)
i = len(nums) - 1 # reset index
else:
i -= 1
return ""
# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
# Notice
# You are not suppose to use the library's sort function for this problem.
# You should do it in-place (sort numbers in the original array).
class SolutionSortColors:
def sortColors(self, nums):
# calculate length of each colors
total = list(0 for x in range(4)) # store length of each color, last is length
for num in nums:
total[num] += 1
index = list(range(3)) # store index for each color
index[0] = 0
index[1] = total[0]
index[2] = total[0] + total[1]
orig = list(index)
orig.append(len(nums))
i = 0
while (i < len(nums)):
num = nums[i]
if (orig[num] <= i and i <= orig[num + 1]):
index[num] += 1
i += 1 # num is already sorted
if (orig[1] <= i):
i = index[1]
if (orig[2] <= i):
i = index[2]
else:
temp = nums[index[num]]
nums[index[num]] = nums[i]
nums[i] = temp
index[num] += 1
# end of while
return nums
# end of SolutionSortColors
# Given a string S, find the longest palindromic substring in S.
# You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
# case: ccabbaccefg
# Manacher algorithm: O (N)
# from center to 2-sides: O(N2)
# optimize: [dabbbbafg], after found abbbba
# all other 'b' can be ignored
# next char, should ensure initial N-len string is palindrome
# next char, if max(substring len) < N, exit
class SolutionLongestPalindrome:
def findMid(self, s, i):
left = i - 1
while (left >= 0):
if (s[left] == s[i]):
left -= 1
else:
break
if (left < 0):
left = 0
else:
left += 1
right = i + 1
while (right < len(s)):
if (s[right] == s[i]):
right += 1
else:
break
if (right >= len(s)):
right = len(s) - 1
else:
right -= 1
return left, right
longestLeft = longestRight = 0
def find(self, s, i):
if not (0 <= i and i < len(s)):
return
mid = self.findMid(s, i)
left = mid[0]
right = mid[1]
while (0 <= left and right < len(s)):
if (s[left] != s[right]):
break
left -= 1
right += 1
if (left < 0):
left = 0
else:
left += 1
if (right >= len(s)):
right = len(s) - 1
else:
right -= 1
if ((right - left) > (self.longestRight - self.longestLeft)):
self.longestLeft = left
self.longestRight = right
pass
# @param {string} s input string
# @return {string} the longest palindromic substring
def longestPalindrome(self, s):
# write your code here
i = len(s) // 2
j = len(s) // 2 + 1
while (i >= 0 or j < len(s)):
self.find(s, i)
self.find(s, j)
i -= 1
j += 1
return s[self.longestLeft : (self.longestRight + 1)]
# def longestPalindrome(self, s):
# # write your code here
# CharBoolFlags.reset()
# currrentStart = i = 0
# midStart = midLen = 0
# result = []
# while True:
# # next char
# ch = s[i]
# if (currrentStart == i):
# result.append(ch)
# prev = ch
# else:
# # compare with prev
# if (prev == ch):
# if (midStart + midLen > 0):
# if (i < midStart + midLen):
# midLen += 1
# else:
# # check mirrored char
# if (ch != s[midStart - (i - (midStart + midLen) + 1)]):
# # mirror is wrong
# el
# else:
# midStart = i - 1
# midLen = 2
# result.append(ch)
# else:
# if (midLen == 0):
# result.append(ch)
# else:
# # check mirrored char
# if ()
# i += 1
#
# # last sub-string is longest
# if (longest < currentLen):
# longest = currentLen
# longest_substring = s[currentStart: currentStart + currentLen]
# return longest_substring
# Given a roman numeral, convert it to an integer.
# The answer is guaranteed to be within the range from 1 to 3999.
# 罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。
# 按照下面的规则可以表示任意正整数。
# 重复数次:一个罗马数字重复几次,就表示这个数的几倍。
# 右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。
# 在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。
# 但是,左减不能跨越等级。比如,99不可以用IC表示,用XCIX表示
class SolutionRemanToInteger:
def romanToInt(self, s):
# decide sign according to priority of operator
if (len(s) == 0):
return 0
roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = roman[s[-1]]
sign = 1
i = -2 # loop from left, start from -2
while (-i <= len(s)):
if (roman[s[i]] < roman[s[i + 1]]):
sign = -1
else:
if (roman[s[i]] > roman[s[i + 1]]):
sign = 1
## if (roman[s[i]] = roman[s[i + 1]]):, sign not changed
result += sign * roman[s[i]]
i -= 1
return result
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
# Notice
# Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
# The solution set must not contain duplicate triplets.
# note: [1,0,-1,-1,-1,-1,0,1,1,1]
class Solution3Sum:
"""
@param numbersbers : Give an array numbersbers of n integer
@return : Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
result = list()
numbers = sorted(numbers)
prev = numbers[0] - 1
last = numbers[-1] + 1
i0 = 0
while (i0 < len(numbers)):
if (prev == numbers[i0]):
# avoid dup triple
i0 += 1
continue
prev = numbers[i0]
last = numbers[-1] + 1
i1 = i0 + 1
i2 = len(numbers) - 1
while (i1 < i2):
sum = numbers[i0] + numbers[i1] + numbers[i2]
if (sum == 0):
# found: add to result
# avoid dup triple
if (last != numbers[i2]):
last = numbers[i2]
result.append([numbers[i0], numbers[i1], numbers[i2]])
i1 += 1
i2 -= 1
else:
if (sum < 0):
i1 += 1
else:
i2 -= 1
i0 += 1
return result
# Longest Common Prefix
# Given k strings, find the longest common prefix (LCP).
class SolutionLarestCommonPrevix:
# @param strs: A list of strings
# @return: The longest common prefix
def longestCommonPrefix(self, strs):
# write your code here
if (len(strs) == 0):
return ''
src = strs[0] # find shortest string
for i in range(1, len(strs)):
if (len(strs[i]) <len(src)):
src = strs[i]
if (len(src) == 0):
return ''
i = 0
while (i < len(src)):
for str in strs:
if (src[i] != str[i]):
if (i == 0):
return ''
else:
return src[:i]
i += 1
return src
# end of SolutionLarestCommonPrevix
# Given n points on a 2D plane, find the maximum number of points
# that lie on the same straight line.
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class SolutionMaxPointsOnALine:
# @param {int[]} points an array of point
# @return {int} an integer
def maxPoints(self, points):
# Write your code here
pass
# Say you have an array for which the ith element is the price of a given stock on day i.
# If you were only permitted to complete at most one transaction
# (ie, buy one and sell one share of the stock), design an algorithm
# to find the maximum profit.
class SolutionBestSellStock1:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
if (len(prices) == 0):
return 0
lowest = prices[0]
i = 0
result = 0
while (i < len(prices)):
if (lowest > prices[i]):
lowest = prices[i]
currentProfit = prices[i] - lowest
if (result < currentProfit):
result = currentProfit
i+= 1
return result
# Say you have an array for which the ith element is the price of a given stock on day i.
# Design an algorithm to find the maximum profit.
# You may complete as many transactions as you like
# (ie, buy one and sell one share of the stock multiple times).
# However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
# solution: buy and sell until price goes down
class SolutionBestSellStock2:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
if (len(prices) <= 1):
return 0
profit = 0
i = 0
while (i < len(prices) - 1):
delta = prices[i + 1] - prices[i]
if (delta >= 0):
profit += delta
i += 1
return profit
# Say you have an array for which the ith element is the price of a given stock on day i.
# Design an algorithm to find the maximum profit. You may complete at most two transactions.
# Notice
# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class SolutionBestSellStock3:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
if (len(prices) <= 1):
return 0
# create pre-profit
preProfit = list()
maxProfit = 0 # reset max profit
i = 0
lowPrice = prices[0]
while (i < len(prices)):
if (lowPrice > prices[i]):
lowPrice = prices[i]
if (maxProfit < prices[i] - lowPrice):
maxProfit = prices[i] - lowPrice
preProfit.append(maxProfit)
i += 1
# print(preProfit)
postProfit = list()
maxProfit = 0 # reset max profit
i = len(prices) - 1
highPrice = prices[i]
while (i >= 0):
if (highPrice < prices[i]):
highPrice = prices[i]
if (maxProfit < highPrice - prices[i]):
maxProfit = highPrice - prices[i]
postProfit.insert(0, maxProfit)
i -= 1
# print(postProfit)
maxProfit = 0
i = 0
while (i < len(prices)):
currentMax = preProfit[i] + postProfit[i]
if (maxProfit < currentMax):
maxProfit = currentMax
i += 1
return maxProfit
class SolutionBestSellStock3_2:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
if (len(prices) <= 1):
return 0
# create pre-profit
preProfit = list([0])
i = 1
lowPrice = prices[0]
while (i < len(prices)):
if (lowPrice > prices[i]):
lowPrice = prices[i]
preProfit.append(max(preProfit[i - 1], prices[i] - lowPrice))
i += 1
# print(preProfit)
postProfit = list([0])
i = len(prices) - 2
highPrice = prices[len(prices) - 1]
while (i >= 0):
if (highPrice < prices[i]):
highPrice = prices[i]
postProfit.insert(0, max(postProfit[0], highPrice - prices[i]))
i -= 1
# print(postProfit)
maxProfit = 0
i = 0
while (i < len(prices)):
maxProfit = max(maxProfit, preProfit[i] + postProfit[i])
i += 1
return maxProfit
# Implement pow(x, n).
# Notice
# You don't need to care about the precision of your answer,
# it's acceptable if the expected answer and your answer 's
# difference is smaller than 1e-3.
class SolutionPowXN:
# @param {double} x the base number
# @param {int} n the power number
# @return {double} the result
def myPow(self, x, n):
# Write your code here
l = list() # store 2, 4, 8..
if (x == 0):
return 0
if (n == 0):
return 1
if (n == 1):
return x
last = x * x
lastPow = 2
sum = 0
ret = 1
isNegative = n < 0
n = abs(n)
loop = 0
while True:
loop += 1
if (sum + lastPow <= n):
sum += lastPow
ret *= last
last = last * last
lastPow = lastPow * 2
else:
last = x * x
lastPow = 2
if (sum == n):
break
if (sum + 1 == n):
ret *= x
break
print('n: %d, loop: %d' % (n, loop))
if (isNegative):
return 1.0 / ret
else:
return ret
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class SolutionSortList:
def merge2Lists(self, l1, l2):
if (l1 == None and l2 == None):
return None
if (l1 == None):
return l2
if (l2 == None):
return l1
h1 = l1
h2 = l2
if (l1.val < l2.val):
ret = l1
h1 = h1.next
else:
ret = l2
h2 = h2.next
cur = ret
while True:
if (h1 == None):
cur.next = h2
break
if (h2 == None):
cur.next = h1
break
if (h1.val < h2.val):
cur.next = h1
h1 = h1.next
else:
cur.next = h2
h2 = h2.next
cur = cur.next
return ret
def sortListWithLen(self, head, listLen):