KK's blog

每天积累多一些

0%

LeetCode 122 Best Time to Buy and Sell Stock II



You are given an integer array prices where prices[i] is the price of a given stock on the i<sup>th</sup> day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.


Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.


Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.


Constraints:

`1 <= prices.length <= 3 104*0 <= prices[i] <= 104`

题目大意:

设计一个算法寻找最大收益。你可以随便完成多少次交易(比如,多次买入卖出)。然而你不能一次进行多次交易。

解题思路:

仍然是求最大利润,可以交易多次,但要先卖再买。容易想到是求所有上升坡的的总和。更简单而言,若将每一个上升坡,分成一小段(每天的交易),求这些小段的和即可。
如:[6, 1, 2, 3, 4]中的1, 2, 3, 4序列来说,对于两种操作方案:
1 在1买入,4卖出
2 在1买入,2卖出同时买入,3卖出同时买入,4卖出
这两种操作下,收益是一样的。这种方法,避免检测下坡以及计算每段的和。

Python代码:

1
2
3
4
5
6
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(1, len(prices)):
if prices[i] - prices[i - 1] > 0:
res += prices[i] - prices[i - 1]
return res

注意事项:

  1. 数组为空

Java代码:

1
2
3
4
5
6
7
8
9
10
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int profit = 0;
for(int i=1;i<prices.length;i++){
if(prices[i-1]<prices[i])
profit += prices[i] - prices[i-1];
}
return profit;
}

算法分析:

时间复杂度为O(n),n为字符串长度,空间复杂度O(1)

相关题目:

LeetCode 121 Best Time to Buy and Sell Stock
LeetCode 122 Best Time to Buy and Sell Stock II
LeetCode 309 Best Time to Buy and Sell Stock with Cooldown
LeetCode 123 Best Time to Buy and Sell Stock III

LeetCode 121 Best Time to Buy and Sell Stock

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

题目大意:

如果你只能进行一次交易(比如购买或者销售一个股票),设计一个算法来获取最大利润。

解题思路:

利润=当前价格-买入价,利润作为第一个变量求其最大值。由于买入价越低,利润可能会越大,所以第二个变量就要不断更新买入价
(最小值)。本题核心思路就是维护两个变量:最低价,利润。为什么不用最高价而选择利润呢?因为最低价和最高价没有顺序,最高价
必须在最低价后面,这样的利润才可实现,但如果是最低价和利润,就能确保这个顺序了,因为利润一定是在最低价后,否则这个利
润为负,不能为最大值。另一种稍麻烦的方法是凡是min更新,最高价就reset为0,大原则就是保持顺序。

注意事项:

  1. 数组为空

Python代码:

1
2
3
4
5
6
7
def maxProfit(self, prices: List[int]) -> int:
min_buy_idx, max_profit = 0, 0
for i in range(len(prices)):
max_profit = max(max_profit, prices[i] - prices[min_buy_idx])
if prices[i] < prices[min_buy_idx]:
min_buy_idx = i
return max_profit

Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int min = prices[0];
int curProfit = 0;
for(int i=1;i<prices.length;i++){
int todayProfit = prices[i]-min;
if(todayProfit>curProfit)
curProfit = todayProfit;
if(min>prices[i])
min = prices[i];
}
return curProfit;
}

算法分析:

时间复杂度为O(n),n为字符串长度,空间复杂度O(1)

相关题目:

LeetCode 121 Best Time to Buy and Sell Stock
LeetCode 122 Best Time to Buy and Sell Stock II
LeetCode 309 Best Time to Buy and Sell Stock with Cooldown
LeetCode 123 Best Time to Buy and Sell Stock III

LeetCode 目录

# Title Difficulty
1 Two Sum Easy
2 Add Two Numbers Medium
3 Longest Substring Without Repeating Characters Medium
4 Median of Two Sorted Arrays Hard
5 Longest Palindromic Substring Medium
6 ZigZag Conversion Medium
7 Reverse Integer Easy
8 String to Integer (atoi) Medium
9 Palindrome Number Easy
10 Regular Expression Matching Hard
11 Container With Most Water Medium
12 Integer to Roman Medium
13 Roman to Integer Easy
14 Longest Common Prefix Easy
15 3Sum Medium
16 3Sum Closest Medium
17 Letter Combinations of a Phone Number Medium
18 4Sum Medium
19 Remove Nth Node From End of List Medium
20 Valid Parentheses Easy
21 Merge Two Sorted Lists Easy
22 Generate Parentheses Medium
23 Merge k Sorted Lists Hard
24 Swap Nodes in Pairs Medium
25 Reverse Nodes in k-Group Hard
26 Remove Duplicates from Sorted Array Easy
27 Remove Element Easy
28 Implement strStr() Easy
29 Divide Two Integers Medium
30 Substring with Concatenation of All Words Hard
31 Next Permutation Medium
32 Longest Valid Parentheses Hard
33 Search in Rotated Sorted Array Medium
34 Search for a Range Medium
35 Search Insert Position Easy
36 Valid Sudoku Medium
37 Sudoku Solver Hard
38 Count and Say Easy
39 Combination Sum Medium
40 Combination Sum II Medium
41 First Missing Positive Hard
42 Trapping Rain Water Hard
43 Multiply Strings Medium
44 Wildcard Matching Hard
45 Jump Game II Hard
46 Permutations Medium
47 Permutations II Medium
48 Rotate Image Medium
49 Group Anagrams Medium
50 Pow(x, n) Medium
51 N-Queens Hard
52 N-Queens II Hard
53 Maximum Subarray Easy
54 Spiral Matrix Medium
55 Jump Game Medium
56 Merge Intervals Medium
57 Insert Interval Hard
58 Length of Last Word Easy
59 Spiral Matrix II Medium
60 Permutation Sequence Medium
61 Rotate List Medium
62 Unique Paths Medium
63 Unique Paths II Medium
64 Minimum Path Sum Medium
65 Valid Number Hard
66 Plus One Easy
67 Add Binary Easy
68 Text Justification Hard
69 Sqrt(x) Easy
70 Climbing Stairs Easy
71 Simplify Path Medium
72 Edit Distance Hard
73 Set Matrix Zeroes Medium
74 Search a 2D Matrix Medium
75 Sort Colors Medium
76 Minimum Window Substring Hard
77 Combinations Medium
78 Subsets Medium
79 Word Search Medium
80 Remove Duplicates from Sorted Array II Medium
81 Search in Rotated Sorted Array II Medium
82 Remove Duplicates from Sorted List II Medium
83 Remove Duplicates from Sorted List Easy
84 Largest Rectangle in Histogram Hard
85 Maximal Rectangle Hard
86 Partition List Medium
87 Scramble String Hard
88 Merge Sorted Array Easy
89 Gray Code Medium
90 Subsets II Medium
91 Decode Ways Medium
92 Reverse Linked List II Medium
93 Restore IP Addresses Medium
94 Binary Tree Inorder Traversal Medium
95 Unique Binary Search Trees II Medium
96 Unique Binary Search Trees Medium
97 Interleaving String Hard
98 Validate Binary Search Tree Medium
99 Recover Binary Search Tree Hard
100 Same Tree Easy
101 Symmetric Tree Easy
102 Binary Tree Level Order Traversal Medium
103 Binary Tree Zigzag Level Order Traversal Medium
104 Maximum Depth of Binary Tree Easy
105 Construct Binary Tree from Preorder and Inorder Traversal Medium
106 Construct Binary Tree from Inorder and Postorder Traversal Medium
107 Binary Tree Level Order Traversal II Easy
108 Convert Sorted Array to Binary Search Tree Easy
109 Convert Sorted List to Binary Search Tree Medium
110 Balanced Binary Tree Easy
111 Minimum Depth of Binary Tree Easy
112 [Path Sum] Easy
113 Path Sum II Medium
114 Flatten Binary Tree to Linked List Medium
115 Distinct Subsequences Hard
116 Populating Next Right Pointers in Each Node Medium
117 Populating Next Right Pointers in Each Node II Medium
118 Pascal’s Triangle Easy
119 Pascal’s Triangle II Easy
120 Triangle Medium
121 Best Time to Buy and Sell Stock Easy
122 Best Time to Buy and Sell Stock II Easy
123 [Best Time to Buy and Sell Stock III] Hard
124 Binary Tree Maximum Path Sum Hard
125 Valid Palindrome Easy
126 Word Ladder II Hard
127 Word Ladder Medium
128 Longest Consecutive Sequence Hard
129 Sum Root to Leaf Numbers Medium
130 Surrounded Regions Medium
131 Palindrome Partitioning Medium
132 Palindrome Partitioning II Hard
133 Clone Graph Medium
134 Gas Station Medium
135 Candy Hard
136 Single Number Easy
137 Single Number II Medium
138 Copy List with Random Pointer Medium
139 Word Break Medium
140 Word Break II Hard
141 Linked List Cycle Easy
142 Linked List Cycle II Medium
143 Reorder List Medium
144 Binary Tree Preorder Traversal Medium
145 Binary Tree Postorder Traversal Hard
146 LRU Cache Hard
147 Insertion Sort List Medium
148 Sort List Medium
149 Max Points on a Line Hard
150 Evaluate Reverse Polish Notation Medium
151 Reverse Words in a String Medium
152 Maximum Product Subarray Medium
153 Find Minimum in Rotated Sorted Array Medium
154 Find Minimum in Rotated Sorted Array II Hard
155 Min Stack Easy
156 Binary Tree Upside Down Medium
157 Read N Characters Given Read4 Easy
158 Read N Characters Given Read4 II - Call multiple times Hard
159 Longest Substring with At Most Two Distinct Characters Hard
160 Intersection of Two Linked Lists Easy
161 One Edit Distance Medium
162 Find Peak Element Medium
163 Missing Ranges Medium
164 Maximum Gap Hard
165 Compare Version Numbers Medium
166 Fraction to Recurring Decimal Medium
167 Two Sum II - Input array is sorted Easy
168 Excel Sheet Column Title Easy
169 Majority Element Easy
170 Two Sum III - Data structure design Easy
171 Excel Sheet Column Number Easy
172 Factorial Trailing Zeroes Easy
173 Binary Search Tree Iterator Medium
174 Dungeon Game Hard
175 Combine Two Tables Easy
176 Second Highest Salary Easy
177 Nth Highest Salary Medium
178 Rank Scores Medium
179 Largest Number Medium
180 Consecutive Numbers Medium
181 Employees Earning More Than Their Managers Easy
182 Duplicate Emails Easy
183 Customers Who Never Order Easy
184 Department Highest Salary Medium
185 Department Top Three Salaries Hard
186 Reverse Words in a String II Medium
187 Repeated DNA Sequences Medium
188 Best Time to Buy and Sell Stock IV Hard
189 Rotate Array Easy
190 Reverse Bits Easy
191 Number of 1 Bits Easy
192 Word Frequency Medium
193 Valid Phone Numbers Easy
194 Transpose File Medium
195 Tenth Line Easy
196 Delete Duplicate Emails Easy
197 Rising Temperature Easy
198 House Robber Easy
199 Binary Tree Right Side View Medium
200 [Number of Islands] Medium
201 Bitwise AND of Numbers Range Medium
202 Happy Number Easy
203 Remove Linked List Elements Easy
204 Count Primes Easy
205 Isomorphic Strings Easy
206 Reverse Linked List Easy
207 Course Schedule Medium
208 Implement Trie (Prefix Tree) Medium
209 Minimum Size Subarray Sum Medium
210 Course Schedule II Medium
211 Add and Search Word - Data structure design Medium
212 Word Search II Hard
213 House Robber II Medium
214 Shortest Palindrome Hard
215 Kth Largest Element in an Array Medium
216 Combination Sum III Medium
217 Contains Duplicate Easy
218 The Skyline Problem Hard
219 Contains Duplicate II Easy
220 Contains Duplicate III Medium
221 Maximal Square Medium
222 Count Complete Tree Nodes Medium
223 Rectangle Area Medium
224 Basic Calculator Hard
225 Implement Stack using Queues Easy
226 Invert Binary Tree Easy
227 Basic Calculator II Medium
228 Summary Ranges Medium
229 Majority Element II Medium
230 Kth Smallest Element in a BST Medium
231 Power of Two Easy
232 Implement Queue using Stacks Easy
233 Number of Digit One Hard
234 Palindrome Linked List Easy
235 Lowest Common Ancestor of a Binary Search Tree Easy
236 Lowest Common Ancestor of a Binary Tree Medium
237 Delete Node in a Linked List Easy
238 Product of Array Except Self Medium
239 Sliding Window Maximum Hard
240 Search a 2D Matrix II Medium
241 Different Ways to Add Parentheses Medium
242 Valid Anagram Easy
243 Shortest Word Distance Easy
244 Shortest Word Distance II Medium
245 Shortest Word Distance III Medium
246 Strobogrammatic Number Easy
247 Strobogrammatic Number II Medium
248 Strobogrammatic Number III Hard
249 Group Shifted Strings Medium
250 Count Univalue Subtrees Medium
251 Flatten 2D Vector Medium
252 Meeting Rooms Easy
253 Meeting Rooms II Medium
254 Factor Combinations Medium
255 Verify Preorder Sequence in Binary Search Tree Medium
256 Paint House Easy
257 Binary Tree Paths Easy
258 Add Digits Easy
259 3Sum Smaller Medium
260 Single Number III Medium
261 Graph Valid Tree Medium
262 Trips and Users Hard
263 Ugly Number Easy
264 Ugly Number II Medium
265 Paint House II Hard
266 Palindrome Permutation Easy
267 Palindrome Permutation II Medium
268 Missing Number Easy
269 Alien Dictionary Hard
270 Closest Binary Search Tree Value Easy
271 Encode and Decode Strings Medium
272 Closest Binary Search Tree Value II Hard
273 Integer to English Words Hard
274 H-Index Medium
275 H-Index II Medium
276 Paint Fence Easy
277 Find the Celebrity Medium
278 First Bad Version Easy
279 Perfect Squares Medium
280 Wiggle Sort Medium
281 Zigzag Iterator Medium
282 Expression Add Operators Hard
283 Move Zeroes Easy
284 Peeking Iterator Medium
285 Inorder Successor in BST Medium
286 Walls and Gates Medium
287 Find the Duplicate Number Medium
288 Unique Word Abbreviation Medium
289 Game of Life Medium
290 Word Pattern Easy
291 Word Pattern II Hard
292 Nim Game Easy
293 Flip Game Easy
294 Flip Game II Medium
295 Find Median from Data Stream Hard
296 Best Meeting Point Hard
297 Serialize and Deserialize Binary Tree Hard
298 Binary Tree Longest Consecutive Sequence Medium
299 Bulls and Cows Medium
300 Longest Increasing Subsequence Medium
301 Remove Invalid Parentheses Hard
302 Smallest Rectangle Enclosing Black Pixels Hard
303 Range Sum Query - Immutable Easy
304 Range Sum Query 2D - Immutable Medium
305 Number of Islands II Hard
306 Additive Number Medium
307 Range Sum Query - Mutable Medium
308 Range Sum Query 2D - Mutable Hard
309 [Best Time to Buy and Sell Stock with Cooldown] Medium
310 [Minimum Height Trees] Medium
311 Sparse Matrix Multiplication Medium
312 [Burst Balloons] Hard
313 Super Ugly Number Medium
314 Binary Tree Vertical Order Traversal Medium
315 Count of Smaller Numbers After Self Hard
316 [Remove Duplicate Letters] Hard
317 Shortest Distance from All Buildings Hard
318 Maximum Product of Word Lengths Medium
319 Bulb Switcher Medium
320 Generalized Abbreviation Medium
321 Create Maximum Number Hard
322 Coin Change Medium
323 Number of Connected Components in an Undirected Graph Medium
324 Wiggle Sort II Medium
325 Maximum Size Subarray Sum Equals k Medium
326 Power of Three Easy
327 Count of Range Sum Hard
328 Odd Even Linked List Medium
329 Longest Increasing Path in a Matrix Hard
330 Patching Array Hard
331 Verify Preorder Serialization of a Binary Tree Medium
332 Reconstruct Itinerary Medium
333 Largest BST Subtree Medium
334 Increasing Triplet Subsequence Medium
335 Self Crossing Hard
336 Palindrome Pairs Hard
337 House Robber III Medium
338 Counting Bits Medium
339 Nested List Weight Sum Easy
340 Longest Substring with At Most K Distinct Characters Hard
341 Flatten Nested List Iterator Medium
342 Power of Four Easy
343 Integer Break Medium
344 Reverse String Easy
345 Reverse Vowels of a String Easy
346 Moving Average from Data Stream Easy
347 Top K Frequent Elements Medium
348 Design Tic-Tac-Toe Medium
349 Intersection of Two Arrays Easy
350 Intersection of Two Arrays II Easy
351 Android Unlock Patterns Medium
352 Data Stream as Disjoint Intervals Hard
353 Design Snake Game Medium
354 Russian Doll Envelopes Hard
355 Design Twitter Medium
356 Line Reflection Medium
357 Count Numbers with Unique Digits Medium
358 Rearrange String k Distance Apart Hard
359 Logger Rate Limiter Easy
360 Sort Transformed Array Medium
361 Bomb Enemy Medium
362 Design Hit Counter Medium
363 Max Sum of Rectangle No Larger Than K Hard
364 Nested List Weight Sum II Medium
365 Water and Jug Problem Medium
366 Find Leaves of Binary Tree Medium
367 Valid Perfect Square Easy
368 Largest Divisible Subset Medium
369 Plus One Linked List Medium
370 Range Addition Medium
371 Sum of Two Integers Easy
372 Super Pow Medium
373 Find K Pairs with Smallest Sums Medium
374 Guess Number Higher or Lower Easy
375 Guess Number Higher or Lower II Medium
376 Wiggle Subsequence Medium
377 Combination Sum IV Medium
378 Kth Smallest Element in a Sorted Matrix Medium
379 Design Phone Directory Medium
380 Insert Delete GetRandom O(1) Medium
381 Insert Delete GetRandom O(1) - Duplicates allowed Hard
382 Linked List Random Node Medium
383 Ransom Note Easy
384 Shuffle an Array Medium
385 Mini Parser Medium
386 Lexicographical Numbers Medium
387 First Unique Character in a String Easy
388 Longest Absolute File Path Medium
389 Find the Difference Easy
390 Elimination Game Medium
391 Perfect Rectangle Hard
392 Is Subsequence Medium
393 UTF-8 Validation Medium
394 Decode String Medium
395 Longest Substring with At Least K Repeating Characters Medium
396 Rotate Function Medium
397 Integer Replacement Medium
398 Random Pick Index Medium
399 Evaluate Division Medium
400 Nth Digit Easy
401 Binary Watch Easy
402 Remove K Digits Medium
403 Frog Jump Hard
404 Sum of Left Leaves Easy
405 Convert a Number to Hexadecimal Easy
406 Queue Reconstruction by Height Medium
407 Trapping Rain Water II Hard
408 Valid Word Abbreviation Easy
409 Longest Palindrome Easy
410 Split Array Largest Sum Hard
411 Minimum Unique Word Abbreviation Hard
412 Fizz Buzz Easy
413 Arithmetic Slices Medium
414 Third Maximum Number Easy
415 Add Strings Easy
416 Partition Equal Subset Sum Medium
417 Pacific Atlantic Water Flow Medium
418 Sentence Screen Fitting Medium
419 Battleships in a Board Medium
420 Strong Password Checker Hard
421 Maximum XOR of Two Numbers in an Array Medium
422 Valid Word Square Easy
423 Reconstruct Original Digits from English Medium
424 Longest Repeating Character Replacement Medium
425 Word Squares Hard
432 All O`one Data Structure Hard
433 Minimum Genetic Mutation Medium
434 Number of Segments in a String Easy
435 Non-overlapping Intervals Medium
436 Find Right Interval Medium
437 Path Sum III Easy
438 Find All Anagrams in a String Easy
439 Ternary Expression Parser Medium
440 K-th Smallest in Lexicographical Order Hard
441 Arranging Coins Easy
442 Find All Duplicates in an Array Medium
443 String Compression Easy
444 Sequence Reconstruction Medium
445 Add Two Numbers II Medium
446 Arithmetic Slices II - Subsequence Hard
447 Number of Boomerangs Easy
448 Find All Numbers Disappeared in an Array Easy
449 Serialize and Deserialize BST Medium
450 Delete Node in a BST Medium
451 Sort Characters By Frequency Medium
452 Minimum Number of Arrows to Burst Balloons Medium
453 Minimum Moves to Equal Array Elements Easy
454 4Sum II Medium
455 Assign Cookies Easy
456 132 Pattern Medium
457 Circular Array Loop Medium
458 Poor Pigs Easy
459 Repeated Substring Pattern Easy
460 LFU Cache Hard
461 Hamming Distance Easy
462 Minimum Moves to Equal Array Elements II Medium
463 Island Perimeter Easy
464 Can I Win Medium
465 Optimal Account Balancing Hard
466 Count The Repetitions Hard
467 Unique Substrings in Wraparound String Medium
468 Validate IP Address Medium
469 Convex Polygon Medium
471 Encode String with Shortest Length Hard
472 Concatenated Words Hard
473 Matchsticks to Square Medium
474 Ones and Zeroes Medium
475 Heaters Easy
476 Number Complement Easy
477 Total Hamming Distance Medium
479 Largest Palindrome Product Easy
480 Sliding Window Median Hard
481 Magical String Medium
482 License Key Formatting Easy
483 Smallest Good Base Hard
484 Find Permutation Medium
485 Max Consecutive Ones Easy
486 Predict the Winner Medium
487 Max Consecutive Ones II Medium
488 Zuma Game Hard
490 The Maze Medium
491 Increasing Subsequences Medium
492 Construct the Rectangle Easy
493 Reverse Pairs Hard
494 Target Sum Medium
495 Teemo Attacking Medium
496 Next Greater Element I Easy
498 Diagonal Traverse Medium
499 The Maze III Hard
500 Keyboard Row Easy
501 Find Mode in Binary Search Tree Easy
502 IPO Hard
503 Next Greater Element II Medium
504 Base 7 Easy
505 The Maze II Medium
506 Relative Ranks Easy
507 Perfect Number Easy
508 Most Frequent Subtree Sum Medium
513 Find Bottom Left Tree Value Medium
514 Freedom Trail Hard
515 Find Largest Value in Each Tree Row Medium
516 Longest Palindromic Subsequence Medium
517 Super Washing Machines Hard
518 Coin Change 2 Medium
520 Detect Capital Easy
521 Longest Uncommon Subsequence IÊ Easy
522 Longest Uncommon Subsequence II Medium
523 Continuous Subarray Sum Medium
524 Longest Word in Dictionary through Deleting Medium
525 Contiguous Array Medium
526 Beautiful Arrangement Medium
527 Word Abbreviation Hard
529 Minesweeper Medium
530 Minimum Absolute Difference in BST Easy
531 Lonely Pixel I Medium
532 K-diff Pairs in an Array Easy
533 Lonely Pixel II Medium
534 Design TinyURL Medium
535 Encode and Decode TinyURL Medium
536 Construct Binary Tree from String Medium
537 Complex Number Multiplication Medium
538 Convert BST to Greater Tree Easy
539 Minimum Time Difference Medium
540 Single Element in a Sorted Array Medium
541 Reverse String II Easy
542 01 Matrix Medium
543 Diameter of Binary Tree Easy
544 Output Contest Matches Medium
545 Boundary of Binary Tree Medium
546 Remove Boxes Hard
547 Friend Circles Medium
548 Split Array with Equal Sum Medium
549 Binary Tree Longest Consecutive Sequence II Medium
551 Student Attendance Record I Easy
552 Student Attendance Record II Hard
553 Optimal Division Medium
554 Brick Wall Medium
555 Split Concatenated Strings Medium
556 Next Greater Element III Medium
557 Reverse Words in a String III Easy
560 Subarray Sum Equals K Medium
561 Array Partition I Easy
562 Longest Line of Consecutive One in Matrix Medium
563 Binary Tree Tilt Easy
564 Find the Closest Palindrome Hard
565 Array Nesting Medium
566 Reshape the Matrix Easy
567 Permutation in String Medium
568 Maximum Vacation Days Hard
569 Median Employee Salary Hard
570 Managers with at Least 5 Direct Reports Medium
571 Find Median Given Frequency of Numbers Hard
572 Subtree of Another Tree Easy
573 Squirrel Simulation Medium
574 Winning Candidate Medium
575 Distribute Candies Easy
576 Out of Boundary Paths Medium
577 Employee Bonus Easy
578 Get Highest Answer Rate Question Medium
579 Find Cumulative Salary of an Employee Hard
580 Count Student Number in Departments Medium
581 Shortest Unsorted Continuous Subarray Easy
582 Kill Process Medium
583 Delete Operation for Two Strings Medium
584 Find Customer Referee Easy
585 Investments in 2016 Medium
586 Customer Placing the Largest Number of Orders Easy
587 Erect the Fence Hard
588 Design In-Memory File System Hard
591 Tag Validator Hard
592 Fraction Addition and Subtraction Medium
593 Valid Square Medium
594 Longest Harmonious Subsequence Easy
595 Big Countries Easy
596 Classes More Than 5 Students Easy
597 Friend Requests I: Overall Acceptance Rate Easy
598 Range Addition II Easy
599 Minimum Index Sum of Two Lists Easy
600 Non-negative Integers without Consecutive Ones Hard
601 Human Traffic of Stadium Hard
602 Friend Requests II: Who Has the Most Friends Medium
603 Consecutive Available Seats Easy
604 Design Compressed String Iterator Easy
605 Can Place Flowers Easy
606 Construct String from Binary Tree Easy
607 Sales Person Easy
608 Tree Node Medium
609 Find Duplicate File in System Medium
610 Triangle Judgement Easy
611 Valid Triangle Number Medium
612 Shortest Distance in a Plane Medium
613 Shortest Distance in a Line Easy
614 Second Degree Follower Medium
615 Average Salary: Departments VS Company Hard
616 Add Bold Tag in String Medium
617 Merge Two Binary Trees Easy
618 Students Report By Geography Hard
619 Biggest Single Number Easy
620 Not Boring Movies Easy
621 Task Scheduler Medium
623 Add One Row to Tree Medium
624 Maximum Distance in Arrays Easy
625 Minimum Factorization Medium
626 Exchange Seats Medium
627 Swap Salary Easy
628 Maximum Product of Three Numbers Easy
629 K Inverse Pairs Array Hard
630 Course Schedule III Hard
631 Design Excel Sum Formula Hard
632 Smallest Range Hard
633 Sum of Square Numbers Easy
634 Find the Derangement of An Array Medium
635 Design Log Storage System Medium
636 Exclusive Time of Functions Medium
637 Average of Levels in Binary Tree Easy
638 Shopping Offers Medium
639 Decode Ways II Hard
640 Solve the Equation Medium
642 Design Search Autocomplete System Hard
643 Maximum Average Subarray I Easy
644 Maximum Average Subarray II Hard
645 Set Mismatch Easy
646 Maximum Length of Pair Chain Medium
647 Palindromic Substrings Medium
648 Replace Words Medium
649 Dota2 Senate Medium
650 2 Keys Keyboard Medium
651 4 Keys Keyboard Medium
652 Find Duplicate Subtrees Medium
653 Two Sum IV - Input is a BST Easy
654 Maximum Binary Tree Medium
655 Print Binary Tree Medium
656 Coin Path Hard
657 Judge Route Circle Easy
658 Find K Closest Elements Medium
659 Split Array into Consecutive Subsequences Medium
660 Remove 9 Hard
661 Image Smoother Easy
662 Maximum Width of Binary Tree Medium
663 Equal Tree Partition Medium
664 Strange Printer Hard
665 Non-decreasing Array Easy
666 Path Sum IV Medium
667 Beautiful Arrangement II Medium
668 Kth Smallest Number in Multiplication Table Hard
669 Trim a Binary Search Tree Easy
670 Maximum Swap Medium
671 Second Minimum Node In a Binary Tree Easy
672 Bulb Switcher II Medium
673 Number of Longest Increasing Subsequence Medium
674 Longest Continuous Increasing Subsequence Easy
675 Cut Off Trees for Golf Event Hard
676 Implement Magic Dictionary Medium
677 Map Sum Pairs Medium
678 Valid Parenthesis String Medium
679 24 Game Hard
680 Valid Palindrome II Easy
681 Next Closest Time Medium
682 Baseball Game Easy
683 K Empty Slots Hard
684 Redundant Connection Medium
685 Redundant Connection II Hard
686 Repeated String Match Easy
687 Longest Univalue Path Easy
688 Knight Probability in Chessboard Medium
689 Maximum Sum of 3 Non-Overlapping Subarrays Hard
690 Employee Importance Easy
691 Stickers to Spell Word Hard
692 Top K Frequent Words Medium
693 Binary Number with Alternating Bits Easy
694 Number of Distinct Islands Medium
695 Max Area of Island Easy
696 Count Binary Substrings Easy
697 Degree of an Array Easy
698 Partition to K Equal Sum Subsets Medium
699 Falling Squares Hard
711 Number of Distinct Islands II Hard
712 Minimum ASCII Delete Sum for Two Strings Medium
713 Subarray Product Less Than K Medium
714 Best Time to Buy and Sell Stock with Transaction Fee Medium
715 Range Module Hard
716 Max Stack Hard
717 1-bit and 2-bit Characters Easy
718 Maximum Length of Repeated Subarray Medium
719 Find K-th Smallest Pair Distance Hard
720 Longest Word in Dictionary Easy
721 Accounts Merge Medium
722 Remove Comments Medium
723 Candy Crush Medium
724 Find Pivot Index Easy
725 Split Linked List in Parts Medium
726 Number of Atoms Hard
727 Minimum Window Subsequence Hard
728 Self Dividing Numbers Easy
729 My Calendar I Medium
730 Count Different Palindromic Subsequences Hard
731 My Calendar II Medium
732 My Calendar III Hard
733 Flood Fill Easy
734 Sentence Similarity Easy
735 Asteroid Collision Medium
736 Parse Lisp Expression Hard
737 Sentence Similarity II Medium
738 Monotone Increasing Digits Medium
739 Daily Temperatures Medium
740 Delete and Earn Medium
741 Cherry Pickup Hard
742 Closest Leaf in a Binary TreeNew Medium
743 Network Delay TimeNew Medium
744 Find Smallest Letter Greater Than TargetNew Easy
745 Prefix and Suffix SearchNew Hard

LeetCode 557 Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note:In the string, each word is separated by single space and there will not be any extra space in the string.

题目大意:

给定字符串,将每个单词逐字符逆置,返回新字符串。注意:字符串中单词之间有且只有1个空格分开。

解题思路:

这里考到StringBuilder,对于字符串连接效率高。还有一个小技巧,就是往输入参数附加一个空格,这样for循环结束后不用特别处理边界情况。
第一种方法是以单词为扫描单位,把字符串分成单词字符串数组,然后把每个单词反转及一个空格加入到结果sb中。
第二种方法是以字符为扫描单位,遇到空格是,就把之前存入的word放入sb中,再进行下一轮word扫描。

注意事项:

  1. 用StringBuilder
  2. 末尾加入空格

Java代码:

第一种方法

1
2
3
4
5
6
7
8
public String reverseWords(String s) {
String[] tokens = s.split(" ");
StringBuilder sb = new StringBuilder();
for(String token : tokens)
sb.append(new StringBuilder(token).reverse().toString()+" ");

return sb.toString().trim();
}

第二种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String reverseWords(String s) {
s = s+" ";
StringBuilder sb = new StringBuilder();
StringBuilder word = new StringBuilder();
for(char c : s.toCharArray()){
if(c!=' ')
word.append(c);
else
{
sb.append(word.reverse().toString()+" ");
word = new StringBuilder();
}
}
return sb.toString().trim();
}

算法分析:

两种方法时间复杂度为O(n),n为字符串长度。第一种方法空间复杂度为O(n),而第二种方法为O(1)

LeetCode 415 Add Strings

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

题目大意:

给出两个字符串形式的非负数num1和num2,返回num1和num2之和。

解题思路:

对每一位进行加法,注意进位和长度不一,类似于merge sort里面merge的实现。最要注意的是进位carry的edge case:for循环后最后值要特别处理。

注意事项:

  1. 三个循环后carry要特殊处理
  2. Python中,题目要求不能用int函数,就只能用ord(num1[i]) - ord(‘0’)

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def addStrings(self, num1: str, num2: str) -> str:
num1, num2 = num1[::-1], num2[::-1]
res = ''
i, j, carry = 0, 0, 0
while i < len(num1) or j < len(num2):
tmp = carry
if i < len(num1):
tmp += ord(num1[i]) - ord('0')
i += 1
if j < len(num2):
tmp += ord(num2[j]) - ord('0')
j += 1
carry = 1 if tmp >= 10 else 0
res += str(tmp % 10)
if carry == 1:
res += str(carry)
return res[::-1]

Java代码:

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
public String addStrings(String num1, String num2) {
StringBuffer sb = new StringBuffer();
int i=num1.length()-1,j=num2.length()-1;
int carry=0;
while(i>=0 && j>=0){
int tmp = Integer.parseInt(num1.charAt(i)+"")+Integer.parseInt(num2.charAt(j)+"")+carry;
if(tmp>=10)
carry = 1;
else carry = 0;
sb.append(tmp%10);
i--;
j--;
}
while(i>=0){
int tmp = Integer.parseInt(num1.charAt(i)+"")+carry;
if(tmp>=10)
carry = 1;
else carry = 0;
sb.append(tmp%10);
i--;
}
while(j>=0){
int tmp = Integer.parseInt(num2.charAt(j)+"")+carry;
if(tmp>=10)
carry = 1;
else carry = 0;
sb.append(tmp%10);
j--;
}
if(carry>0)
sb.append(carry);
return sb.reverse().toString();
}

算法分析:

时间复杂度为O(n),n为字符串较长者长度。空间复杂度为O(1)

Free mock interview