-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.xml
5176 lines (4682 loc) · 219 KB
/
search.xml
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
<?xml version="1.0" encoding="utf-8"?>
<search>
<entry>
<title><![CDATA[Leetcode Counting Bits(Java)]]></title>
<url>http://yoursite.com/2016/03/25/Leetcode-Counting-Bits-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.</p>
<p>Example:<br>For num = 5 you should return [0,1,1,2,1,2].</p>
<p>Follow up:</p>
<p>It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?<br>Space complexity should be O(n).<br>Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.<br>Hint:</p>
<p>You should make use of what you have produced already.<br>Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.<br>Or does the odd/even status of the number help you in calculating the number of 1s?</p>
<p><strong>Thinking:</strong></p>
<p>We can divide the numbers into several groups and calculate the current elements based on the prvious ones. For example, in the group of [0-3] and [4-7], the later group’s elements have always one more 1 than the previous group.</p>
<p><strong>Solution:</strong></p>
<pre><code>public int[] countBits(int num) {
int[] res = new int[num+1];
res[0] = 0;
int flag = 1;
for (int i = 1; i <= num; i++) {
if (i / flag == 2) flag *= 2;
res[i] = res[i % flag] + 1;
}
return res;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode Largest Number(Java)]]></title>
<url>http://yoursite.com/2016/03/10/Leetcode-Largest-Number-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a list of non negative integers, arrange them such that they form the largest number.</p>
<p>For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.</p>
<p>Note: The result may be very large, so you need to return a string instead of an integer.</p>
<p><strong>Thinking:</strong></p>
<p>I suppose we should sort the numbers in order. For example, if there are two nums, we convert them into strings. Then compare the connection of s1 + s2 and connection s2 + s1. Make sure the compare method. Then what we need is connecting them together.</p>
<p><strong>Solution:</strong></p>
<pre><code>public String largestNumber(int[] nums) {
PriorityQueue<String> maxHeap = new PriorityQueue<String>(new NumComparator());
StringBuilder res = new StringBuilder();
for (int num: nums)
maxHeap.add(Integer.toString(num));
while (!maxHeap.isEmpty())
res.append(maxHeap.poll());
return res.toString().charAt(0) == '0'? "0" : res.toString();
}
public class NumComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
String str1 = s1 + s2;
String str2 = s2 + s1;
return str2.compareTo(str1);
}
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode Reverse Words in a String(Java)]]></title>
<url>http://yoursite.com/2016/03/10/Leetcode-Reverse-Words-in-a-String-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given an input string, reverse the string word by word.</p>
<p>For example,<br>Given s = “the sky is blue”,<br>return “blue is sky the”.</p>
<p>Update (2015-02-12):<br>For C programmers: Try to solve it in-place in O(1) space.</p>
<p>Clarification:<br>What constitutes a word?<br>A sequence of non-space characters constitutes a word.<br>Could the input string contain leading or trailing spaces?<br>Yes. However, your reversed string should not contain leading or trailing spaces.<br>How about multiple spaces between two words?<br>Reduce them to a single space in the reversed string.</p>
<p><strong>Thinking:</strong></p>
<p>We can use Java API to easily split the String into pieces with String[] strs = s.trim().split(“\s+”). We should to notice the “\s+” match one or many whitespaces.</p>
<p><strong>Solution:</strong></p>
<pre><code>public String reverseWords(String s) {
String[] strs = s.trim().split("\\s+");
StringBuilder res = new StringBuilder();
for (int i = strs.length-1; i >= 0; i--)
res.append(strs[i] + " ");
return res.toString().trim();
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode Wiggle Sort II(Java)]]></title>
<url>http://yoursite.com/2016/03/09/Leetcode-Wiggle-Sort-II-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….</p>
<p>Example:<br>(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].<br>(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].</p>
<p>Note:<br>You may assume all input has valid answer.</p>
<p>Follow Up:<br>Can you do it in O(n) time and/or in-place with O(1) extra space?</p>
<p><strong>Thinking:</strong></p>
<p>Firstly, we get information from the question is that we should divide all the elements into two groups. One is smaller ones, and the other is greater ones. Then we need to get the median to group them.</p>
<p>So we need the method called quickselect which is used in the kth largest element to get the median. Then rewire the element to new index which use (1+2<em>(i)) % (n|1). It(A(i) = nums[(1+2</em>(i)) % (n|1)]) means:</p>
<p>If the length of array is 10, then</p>
<p>Accessing A(0) actually accesses nums[1].<br>Accessing A(1) actually accesses nums[3].<br>Accessing A(2) actually accesses nums[5].<br>Accessing A(3) actually accesses nums[7].<br>Accessing A(4) actually accesses nums[9].<br>Accessing A(5) actually accesses nums[0].<br>Accessing A(6) actually accesses nums[2].<br>Accessing A(7) actually accesses nums[4].<br>Accessing A(8) actually accesses nums[6].<br>Accessing A(9) actually accesses nums[8].</p>
<p>We firstly put ones greater than median, then median, finally smaller than median. We’ll get the result.</p>
<p>There are some details to notice:</p>
<ol>
<li>In the rewiring process, we need to distinguish whether the length of the array is odd or even. Use the (n|1).</li>
<li>In the 3 way partition process, when move larger element to the head, we don’t need to check it again. Because the element move from the head to the current position is checked before. On the other hand, the element which is moved from the current position to tail, we need to check it again.</li>
</ol>
<p><strong>Solution:</strong></p>
<pre><code>public void wiggleSort(int[] nums) {
int len = nums.length;
if (len < 2) return;
quickselect(nums, (len-1)/2);
int mid = nums[(len-1)/2];
int i = 0, j = len - 1, cur = 0;
while (cur <= j) {
if (nums[(2*cur+1)%(len|1)] > mid)
swap(nums, (2*(cur++)+1)%(len|1), (2*(i++)+1)%(len|1));
else if (nums[(2*cur+1)%(len|1)] < mid)
swap(nums, (2*(cur)+1)%(len|1), (2*(j--)+1)%(len|1));
else
cur++;
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void quickselect(int[] nums, int n) {
int low = 0, high = nums.length-1;
while (true) {
int i = partition(nums, low, high);
if (i == n) return;
else if (i < n) low = i + 1;
else high = i - 1;
}
}
private int partition (int[] nums, int left, int right) {
int pivot = nums[left];
int storeIndex = left;
nums[left] = nums[right];
for (int i = left; i < right; i++) {
if (nums[i] <= pivot)
swap(nums, storeIndex++, i);
}
nums[right] = nums[storeIndex];
nums[storeIndex] = pivot;
return storeIndex;
}
</code></pre><p>Reference: <a href="https://leetcode.com/discuss/77133/o-n-o-1-after-median-virtual-indexing" target="_blank" rel="external">https://leetcode.com/discuss/77133/o-n-o-1-after-median-virtual-indexing</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode Range Sum Query 2D - Immutable(Java)]]></title>
<url>http://yoursite.com/2016/03/08/Leetcode-Range-Sum-Query-2D-Immutable-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).</p>
<p><img src="https://leetcode.com/static/images/courses/range_sum_query_2d.png" alt=""></p>
<p>Range Sum Query 2D<br>The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.</p>
<p>Example:</p>
<pre><code>Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
</code></pre><p>Note:</p>
<p>1.You may assume that the matrix does not change.</p>
<p>2.There are many calls to sumRegion function.</p>
<p>3.You may assume that row1 ≤ row2 and col1 ≤ col2.</p>
<p><strong>Thinking:</strong></p>
<p>I see this problem as a matrix caculating. We should get the sum of the current i, j (row and column index) from 0, 0. Then caculate the region sum from previous stored values.</p>
<p><strong>Solution:</strong></p>
<pre><code>private int[][] sumMatrix = null;
public NumMatrix(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int m = matrix.length;
int n = matrix[0].length;
this.sumMatrix = new int[m+1][n+1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
sumMatrix[i][j] = sumMatrix[i-1][j] + sumMatrix[i][j-1] + matrix[i-1][j-1] - sumMatrix[i-1][j-1];
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return sumMatrix[row2+1][col2+1] + sumMatrix[row1][col1] - sumMatrix[row2+1][col1] - sumMatrix[row1][col2+1];
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[The Zen of Python]]></title>
<url>http://yoursite.com/2016/03/08/The-Zen-of-Python/</url>
<content type="html"><![CDATA[<p><strong>The Zen of Python:</strong></p>
<p>Beautiful is better than ugly.</p>
<p>Explicit is better than implicit.</p>
<p>Simple is better than complex.</p>
<p>Complex is better than complicated.</p>
<p>Flat is better than nested.</p>
<p>Sparse is better than dense.</p>
<p>Readability counts.</p>
<p>Special cases aren’t special enough to break the rules.</p>
<p>Although practicality beats purity.</p>
<p>Errors should never pass silently.</p>
<p>Unless explicitly silenced.</p>
<p>In the face of ambiguity, refuse the temptation to guess.</p>
<p>There should be one– and preferably only one –obvious way to do it.</p>
<p>Although that way may not be obvious at first unless you’re Dutch.</p>
<p>Now is better than never.</p>
<p>Although never is often better than <em>right</em> now.</p>
<p>If the implementation is hard to explain, it’s a bad idea.</p>
<p>If the implementation is easy to explain, it may be a good idea.</p>
<p>Namespaces are one honking great idea – let’s do more of those!</p>
<p>(Reference: <a href="https://www.python.org/dev/peps/pep-0020/" target="_blank" rel="external">https://www.python.org/dev/peps/pep-0020/</a>)</p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Reconstruct Itinerary(Java)]]></title>
<url>http://yoursite.com/2016/03/08/Leetcode-Reconstruct-Itinerary-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.</p>
<p>Note:<br>If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary </p>
<p> 1.[“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].</p>
<p> 2.All airports are represented by three capital letters (IATA code).</p>
<p> 3.You may assume all tickets form at least one valid itinerary.</p>
<p>Example 1:</p>
<pre><code>tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
</code></pre><p>Return </p>
<pre><code>["JFK", "MUC", "LHR", "SFO", "SJC"].
</code></pre><p>Example 2:</p>
<pre><code>tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
</code></pre><p>Return </p>
<pre><code>["JFK","ATL","JFK","SFO","ATL","SFO"].
</code></pre><p>Another possible reconstruction is [“JFK”,”SFO”,”ATL”,”JFK”,”ATL”,”SFO”]. But it is larger in lexical order.</p>
<p><strong>Thinking:</strong></p>
<p>We need to use dfs to travse all the graph and record the graph. But we need to record it in order. So it should be stored in PriorityQueue and store the route while visiting. If it’s stuck we back up but also record the previous information, because we know there are other ways to get there. Until all the edges are visited once, it’s finished.</p>
<p><strong>Solution:</strong></p>
<pre><code>List<String> res = new ArrayList<String>();
HashMap<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>();
public List<String> findItinerary(String[][] tickets) {
for (String[] ticket: tickets)
map.computeIfAbsent(ticket[0], k -> new PriorityQueue<String>()).add(ticket[1]);
visit("JFK");
return res;
}
private void visit(String cur) {
while (map.containsKey(cur) && !map.get(cur).isEmpty())
visit(map.get(cur).poll());
res.add(0, cur);
}
</code></pre><p>Reference: <a href="https://leetcode.com/discuss/84659/short-ruby-python-java-c" target="_blank" rel="external">https://leetcode.com/discuss/84659/short-ruby-python-java-c</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Maximum Product Subarray(Java)]]></title>
<url>http://yoursite.com/2016/03/07/Leetcode-Maximum-Product-Subarray-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Find the contiguous subarray within an array (containing at least one number) which has the largest product.</p>
<p>For example, given the array [2,3,-2,4],<br>the contiguous subarray [2,3] has the largest product = 6.</p>
<p><strong>Thinking:</strong></p>
<p>This problem is similiar with the MaxSubArray. One thing we need to notice is that we should maintian another variable which is the minimum value of the negative value. When it multiple the negtive value in the array, it maybe the maximum.</p>
<p><strong>Solution:</strong></p>
<pre><code>public int maxProduct(int[] nums) {
int l = nums.length;
int max = nums[0];
int maxhere = nums[0];
int minhere = nums[0];
for (int i = 1; i < l; i++) {
if (nums[i] >= 0) {
maxhere = Math.max(maxhere*nums[i], nums[i]);
minhere = Math.min(minhere*nums[i], nums[i]);
} else {
int temp = maxhere;
maxhere = Math.max(minhere*nums[i], nums[i]);
minhere = Math.min(temp*nums[i], nums[i]);
}
max = Math.max(maxhere, max);
}
return max;
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Evaluate Reverse Polish Notation(Java)]]></title>
<url>http://yoursite.com/2016/03/07/Leetcode-Evaluate-Reverse-Polish-Notation-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Evaluate the value of an arithmetic expression in Reverse Polish Notation.</p>
<p>Valid operators are +, -, *, /. Each operand may be an integer or another expression.</p>
<p>Some examples:</p>
<pre><code>["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
</code></pre><p><strong>Thinking:</strong></p>
<p>We should use stack and scan the elements of this string array. Whenever we get the operator, we pop element from the stack and push new element to the stack.</p>
<p><strong>Solutioin:</strong></p>
<pre><code>public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (String s: tokens) {
if (s.equals("+")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num1+num2);
}
else if (s.equals("-")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2-num1);
}
else if (s.equals("*")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num1*num2);
}
else if (s.equals("/")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2/num1);
}
else
stack.push(Integer.parseInt(s));
}
return stack.pop();
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Increasing Triplet Subsequence(Java)]]></title>
<url>http://yoursite.com/2016/03/07/Leetcode-Increasing-Triplet-Subsequence-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.</p>
<p>Formally the function should:<br>Return true if there exists i, j, k<br>such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.<br>Your algorithm should run in O(n) time complexity and O(1) space complexity.</p>
<p>Examples:<br>Given [1, 2, 3, 4, 5],<br>return true.</p>
<p>Given [5, 4, 3, 2, 1],<br>return false.</p>
<p><strong>Thinking:</strong></p>
<p>We need to implement this algorithm in linear time and constant space. So we need to scan this array once and record the information needed in one time. We need to variable to record the information, the first one is the minimum of this array, and the second one is the number which is bigger than its previous elements. If one element is bigger than it, the result will be true. Otherwise, we should update the two variables’ values.</p>
<p><strong>Solution:</strong></p>
<pre><code>public boolean increasingTriplet(int[] nums) {
int l = nums.length;
if (l < 3) return false;
int min = nums[0];
int secmin = Integer.MAX_VALUE;
for (int i = 1; i < l; i++) {
if (nums[i] > secmin) return true;
else if (nums[i] <= min) min = nums[i];
else if (nums[i] < secmin) secmin = nums[i];
}
return false;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Shortest Path Problem]]></title>
<url>http://yoursite.com/2016/03/06/Shortest-Path-Problem/</url>
<content type="html"><![CDATA[<p><strong>Shorstest Path Problem Categories:</strong></p>
<ol>
<li>From a speicific start point;</li>
<li>To a specific end point;</li>
<li>Start and end with a specific point;</li>
<li>Search for all the shortest path in every pair nodes.</li>
</ol>
<p><strong>Dijkstra:</strong></p>
<p>This algorithm is aiming at caculating all the shortest paths from every point to a specific start point. And it’s a greedy algorithm.</p>
<p>Algorithm:</p>
<ol>
<li>Set the distance to the start node as infinity to all the nodes except the start node.</li>
<li>Initial a set which conclude the added nodes, and another set for unvisited nodes.</li>
<li>For the added nodes set, we find the shortest edge from adjancent nodes crossing this set in unvisited set. And add the adjancent node to the added added nodes.</li>
<li>Update the distances of nodes from start node which connect to the last added node.</li>
<li>Do step 3 and 4 repeatedly until all the nodes are in the added set.</li>
</ol>
<p>Pseudoode:</p>
<pre><code>function Dijkstra(Graph, source):
create vertex set Q
for each vertex v in Graph: // Initialization
dist[v] ← INFINITY // Unknown distance from source to v
prev[v] ← UNDEFINED // Previous node in optimal path from source
add v to Q // All nodes initially in Q (unvisited nodes)
dist[source] ← 0 // Distance from source to source
while Q is not empty:
u ← vertex in Q with min dist[u] // Source node will be selected first
remove u from Q
for each neighbor v of u: // where v is still in Q.
alt ← dist[u] + length(u, v)
if alt < dist[v]: // A shorter path to v has been found
dist[v] ← alt
prev[v] ← u
return dist[], prev[]
</code></pre><p>Java Code:</p>
<pre><code>public static void dijkstra(int[][] edges, int s, int[] dist, int[] pre) {
int n = edges.length;
HashSet<Integer> set = new HashSet<Integer>(n);
for (int i = 0; i < n; i++) {
dist[i] = Integer.MAX_VALUE;
set.add(i);
}
dist[s] = 0;
while (!set.isEmpty()) {
int min = findMin(set, dist);
for (int i = 0; i < n; i++) {
if (edges[min][i] != -1) { // find the neighbors of the node
if (dist[i] < dist[min] + edges[min][i]) { //relaxation
dist[i] = dist[min] + edges[min][i];
pre[i] = min;
}
}
}
}
}
private static int findMin(Set set, int[] dist) {
int min = Integer.MAX_VALUE, minIdx = -1;
for (int i = 0; i < dist.length; i++) {
if (set.contains(i) && dist[i] < min) {
min = dist[i];
minIdx = i;
}
}
set.remove(minIdx);
return minIdx;
}
</code></pre><p>Running Time:</p>
<p>O(E*lgv)</p>
<p>If use the Fibonacci heap -> O(V*lgV + E)</p>
<p><strong>Bellman Ford:</strong></p>
<p>Aimming at searching for the shortest path from a specific start node. It is useful also for the graph containing the negative edges. It’s a dynamic programming algorithm.</p>
<p>Algorithm:</p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Maximal Square(Java)]]></title>
<url>http://yoursite.com/2016/02/27/Leetcode-Maximal-Square-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.</p>
<p>For example, given the following matrix:</p>
<pre><code>1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
</code></pre><p>Return 4.</p>
<p><strong>Thinking:</strong></p>
<p>IIf the [i-1][j], [i][j-1] and [i-1][j-1] all have the same length of ‘1’ edge and the [i][j] is ‘1’, the length of the square can increase.</p>
<p><strong>Solution:</strong></p>
<pre><code>public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int res = 0;
int[][] opt = new int[m+1][n+1];
for (int i = 1; i <= m; i++){
for (int j = 1; j <= n; j++) {
if (matrix[i-1][j-1] == '1') {
opt[i][j] = Math.min(opt[i-1][j-1], Math.min(opt[i-1][j], opt[i][j-1])) + 1;
res = Math.max(res, opt[i][j]);
}
}
}
return res * res;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Reorder List(Java)]]></title>
<url>http://yoursite.com/2016/02/27/Leetcode-Reorder-List-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a singly linked list L: L0→L1→…→Ln-1→Ln,<br>reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…</p>
<p>You must do this in-place without altering the nodes’ values.</p>
<p>For example,<br>Given {1,2,3,4}, reorder it to {1,4,2,3}.</p>
<p><strong>Thinking:</strong></p>
<p>We need three steps to finish this operation. The first one is to find the middle in the linked list. The second one is to reverse the second half of this linked list. The final one is to link these two parts again.</p>
<p><strong>Solution:</strong></p>
<pre><code>public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
ListNode slow = head, fast = head.next, preMiddle, preCurrent, current, p, q;
//find the middle
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//reverse the second half
preMiddle = slow;
preCurrent = slow.next;
while (preCurrent.next != null) {
current = preCurrent.next;
preCurrent.next = current.next;
current.next = preMiddle.next;
preMiddle.next = current;
}
//connect two parts
p = head;
q = preMiddle.next;
while (p != preMiddle) {
preMiddle.next = q.next;
q.next = p.next;
p.next = q;
p = q.next;
q = preMiddle.next;
}
}
</code></pre><p>Reference:<a href="https://leetcode.com/discuss/35599/java-solution-with-3-steps" target="_blank" rel="external">https://leetcode.com/discuss/35599/java-solution-with-3-steps</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Word Ladder(Java)]]></title>
<url>http://yoursite.com/2016/02/26/Leetcode-Word-Ladder-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:</p>
<p>Only one letter can be changed at a time<br>Each intermediate word must exist in the word list<br>For example,</p>
<p>Given:<br>beginWord = “hit”<br>endWord = “cog”<br>wordList = [“hot”,”dot”,”dog”,”lot”,”log”]<br>As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,<br>return its length 5.</p>
<p>Note:<br>Return 0 if there is no such transformation sequence.<br>All words have the same length.<br>All words contain only lowercase alphabetic characters.</p>
<p><strong>Thinking:</strong></p>
<p>We can search the result from the start word. At every step, we change the every index of the start string and check if it’s in the WordList. If it’s in the range, then we add it to our nodes. Do it like a BFS search. Also in order to be more efficient, we can search also from the end word.</p>
<p><strong>Solution:</strong></p>
<pre><code>public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
if (beginWord.equals(endWord)) return 1;
Set<String> startSet = new HashSet<String>();
Set<String> endSet = new HashSet<String>();
int res = 1;
startSet.add(beginWord);
endSet.add(endWord);
while (!wordList.isEmpty() && !startSet.isEmpty() && !endSet.isEmpty()) {
res++;
Set<String> tempSet = new HashSet<String>();
for (String nWord: startSet) {
wordList.remove(nWord);
for (String ele: check(nWord, wordList)) {
if (endSet.contains(ele)) return res;
tempSet.add(ele);
}
}
startSet = tempSet;
tempSet = new HashSet<String>();
res++;
for (String nWord: endSet) {
wordList.remove(nWord);
for (String ele: check(nWord, wordList)) {
if (startSet.contains(ele)) return res;
tempSet.add(ele);
}
}
endSet = tempSet;
}
return 0;
}
private List<String> check(String word, Set<String> wordList) {
List<String> res = new ArrayList<String>();
int len = word.length();
if (len == 1) {
res.addAll(wordList);
return res;
}
for (int i = 0; i < len; i++) {
char[] chs = word.toCharArray();
for (char j = 'a'; j <= 'z'; j++) {
chs[i] = j;
String temp = String.valueOf(chs);
if (wordList.contains(temp)) res.add(temp);
}
}
return res;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Validate Binary Search Tree(Java)]]></title>
<url>http://yoursite.com/2016/02/26/Leetcode-Validate-Binary-Search-Tree-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a binary tree, determine if it is a valid binary search tree (BST).</p>
<p>Assume a BST is defined as follows:</p>
<p>The left subtree of a node contains only nodes with keys less than the node’s key.<br>The right subtree of a node contains only nodes with keys greater than the node’s key.<br>Both the left and right subtrees must also be binary search trees.</p>
<p><strong>Thinking:</strong></p>
<p>We should use dfs check the root of the range and both its left child and right child.</p>
<p><strong>Solution:</strong></p>
<pre><code>public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long a, long b) {
if (root == null) return true;
if (root.val <= a || root.val >= b) return false;
return helper(root.left, a, root.val<b? root.val:b) && helper(root.right, root.val>a? root.val:a, b);
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Decode Ways(Java)]]></title>
<url>http://yoursite.com/2016/02/26/Leetcode-Decode-Ways-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>A message containing letters from A-Z is being encoded to numbers using the following mapping:</p>
<p>‘A’ -> 1<br>‘B’ -> 2<br>…<br>‘Z’ -> 26<br>Given an encoded message containing digits, determine the total number of ways to decode it.</p>
<p>For example,<br>Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).</p>
<p>The number of ways decoding “12” is 2.</p>
<p><strong>Thinking:</strong></p>
<p>If we use the recursive way, we should see that the search tree will go down like check [0],[0,1], then [1],[1,2] and [2],[2,3] then [2], [2,3] and [3],[3,4] and [3],[3,4] and [4],[4,5] … There are some nodes are repeated. So we can use interation from bottom to root to store the number of paths in every index of string.</p>
<p><strong>Solution:</strong></p>
<pre><code>public int numDecodings(String s) {
int l = s.length();
if (l == 0) return 0;
int[] counts = new int[l+1];
counts[l] = 1;
if (s.charAt(l-1) != '0') counts[l-1] = 1;
for (int i = l-2; i >=0; i--) {
if (s.charAt(i) == '0') continue;
counts[i] = Integer.parseInt(s.substring(i, i+2)) <=26? counts[i+1]+counts[i+2] : counts[i+1];
}
return counts[0];
}
</code></pre><p>Reference: <a href="https://leetcode.com/discuss/8527/dp-solution-java-for-reference" target="_blank" rel="external">https://leetcode.com/discuss/8527/dp-solution-java-for-reference</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Simplify Path(Java)]]></title>
<url>http://yoursite.com/2016/02/25/Leetcode-Simplify-Path-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given an absolute path for a file (Unix-style), simplify it.</p>
<p>For example,<br>path = “/home/“, => “/home”<br>path = “/a/./b/../../c/“, => “/c”<br>click to show corner cases.</p>
<p>Corner Cases:<br>Did you consider the case where path = “/../“?<br>In this case, you should return “/“.<br>Another corner case is the path might contain multiple slashes ‘/‘ together, such as “/home//foo/“.<br>In this case, you should ignore redundant slashes and return “/home/foo”.</p>
<p><strong>Thinking:</strong></p>
<p>The file system is like a tree, and finding path of this tree is like a dfs process. So we can use stack to track the node of dfs. If the string is “..”, we go back, otherwise go to the given dirctory.</p>
<p><strong>Solution:</strong></p>
<pre><code>public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] paths = path.split("/");
for (String p: paths) {
p = p.trim();
if (p.equals("") || p.equals(".")) continue;
if (p.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
continue;
}
stack.push(p);
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty())
res.insert(0, "/".concat(stack.pop()));
return res.length() == 0? "/":res.toString();
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Word Search(Java)]]></title>
<url>http://yoursite.com/2016/02/25/Leetcode-Word-Search-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a 2D board and a word, find if the word exists in the grid.</p>
<p>The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.</p>
<p>For example,<br>Given board =</p>
<p>[<br> [‘A’,’B’,’C’,’E’],<br> [‘S’,’F’,’C’,’S’],<br> [‘A’,’D’,’E’,’E’]<br>]<br>word = “ABCCED”, -> returns true,<br>word = “SEE”, -> returns true,<br>word = “ABCB”, -> returns false.</p>
<p><strong>Thinking:</strong></p>
<p>I assume it’s graph and do dfs in this 2d array. Start from every point and search the result until find the solution or failure. In this process, we need to record the visitied set. In my solution, I used the hashset. But in more efficient way, we can use bit manipulate to mask the visited element.</p>
<p><strong>Solution:</strong></p>
<p>My solution(use HashSet):</p>
<pre><code>public boolean exist(char[][] board, String word) {
int m = board.length;
if (m == 0) return false;
int n = board[0].length;
Set<Integer> record = new HashSet<Integer>();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (backtracking(board, word, 0, i, j, record)) return true;
return false;
}
private boolean backtracking(char[][] board, String word, int index, int i, int j, Set<Integer> record) {
if (board[i][j] == word.charAt(index) && !record.contains(i*board[0].length+j)){
if (index == word.length()-1) return true;
boolean res = false;
record.add(i*board[0].length+j);
if (i-1>=0) res |= backtracking(board, word, index+1, i-1, j, record);
if (!res && i+1<board.length) res |= backtracking(board, word, index+1, i+1, j, record);
if (!res && j-1>=0) res |= backtracking(board, word, index+1, i, j-1, record);
if (!res && j+1<board[0].length) res |= backtracking(board, word, index+1, i, j+1, record);
record.remove(i*board[0].length+j);
return res;
}
return false;
}
</code></pre><p>use the mask:</p>
<pre><code>public boolean exist(char[][] board, String word) {
char[] w = word.toCharArray();
for (int y=0; y<board.length; y++) {
for (int x=0; x<board[y].length; x++) {
if (exist(board, y, x, w, 0)) return true;
}
}
return false;
}
private boolean exist(char[][] board, int y, int x, char[] word, int i) {
if (i == word.length) return true;
if (y<0 || x<0 || y == board.length || x == board[y].length) return false;
if (board[y][x] != word[i]) return false;
board[y][x] ^= 256;
boolean exist = exist(board, y, x+1, word, i+1)
|| exist(board, y, x-1, word, i+1)
|| exist(board, y+1, x, word, i+1)
|| exist(board, y-1, x, word, i+1);
board[y][x] ^= 256;
return exist;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Spiral Matrix(Java)]]></title>
<url>http://yoursite.com/2016/02/23/Leetcode-Spiral-Matrix-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.</p>
<p>For example,<br>Given the following matrix:</p>
<pre><code>[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
</code></pre><p>You should return [1,2,3,6,9,8,7,4,5].</p>
<p><strong>Thinking:</strong></p>
<p>There are four directions can go, move according to the order of right, down, left, up and check the bound of moving.</p>
<p><strong>Solution:</strong></p>
<pre><code>public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
int m = matrix.length;
if (m == 0) return res;
int n = matrix[0].length;
int direction = 0;//0right, 1down, 2left, 3up
int i = 0, j = 0;//position
int c0 = 1, c1 = 1, c2 = 0, c3 = 1;//row and column limit
while (c0 + c2 - 1 <= n && c1 + c3 - 1 <= m) {
res.add(matrix[i][j]);
switch (direction) {
case 0:
if (j == n-c0){
direction = (direction+1) % 4;
c0++;
res.remove(res.size()-1);
}
else
j++;
break;
case 1:
if (i == m-c1){
direction = (direction+1) % 4;
c1++;
res.remove(res.size()-1);
}
else
i++;
break;
case 2:
if (j == c2){
direction = (direction+1) % 4;
c2++;
res.remove(res.size()-1);
}
else
j--;
break;
case 3:
if (i == c3){
direction = (direction+1) % 4;
c3++;
res.remove(res.size()-1);
}
else
i--;
break;
}
}
res.add(matrix[i][j]);
return res;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Multiply Strings(Java)]]></title>
<url>http://yoursite.com/2016/02/23/Leetcode-Multiply-Strings-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given two numbers represented as strings, return multiplication of the numbers as a string.</p>
<p>Note: The numbers can be arbitrarily large and are non-negative.</p>
<p><strong>Thinking:</strong></p>
<p>Simulate the process of multiplying.</p>
<p><img src="https://drscdn.500px.org/photo/130178585/m%3D2048/300d71f784f679d5e70fadda8ad7d68f" alt=""></p>
<p><strong>Solution:</strong> (Record the result from low digits to high digits in array)</p>
<pre><code>public String multiply(String num1, String num2) {
int l1 = num1.length(), l2 = num2.length();
int[] res = new int[l1+l2];
for (int i = l1-1; i >= 0; i--) {
for (int j = l2-1; j >= 0; j--){
int index = l1+l2-i-j-2;
res[index] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
res[index+1] += res[index] / 10;
res[index] = res[index] % 10;
}
}
StringBuilder fres = new StringBuilder();
for (int i = res.length-1; i >= 0; i--)
if (!(fres.length() == 0 && res[i] == 0)) fres.append(res[i]);
return fres.length() == 0? "0":fres.toString();
}
</code></pre><p>A little improvement which record the result from high to low digits in array:</p>
<p>public String multiply(String num1, String num2) {<br> int m = num1.length(), n = num2.length();<br> int[] pos = new int[m + n];</p>
<pre><code>for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j, p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
</code></pre><p>}</p>
<p>Reference: <a href="https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation" target="_blank" rel="external">https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Rotate List(Java)]]></title>
<url>http://yoursite.com/2016/02/23/Leetcode-Rotate-List-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a list, rotate the list to the right by k places, where k is non-negative.</p>
<p>For example:<br>Given 1->2->3->4->5->NULL and k = 2,<br>return 4->5->1->2->3->NULL.</p>
<p><strong>Thinking:</strong></p>
<p>Firstly, count the length of the linked list. Then get the n-k th node. Finnaly, change the pointer of it and the tail.</p>
<p><strong>Solution:</strong></p>
<pre><code>public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
ListNode p = head;
int count = 1;
while (p.next != null) {
p = p.next;
count++;
}
if (k == count) return head;
p.next = head;
p = head;
for (int i = 1; i < count - k%count; i++) {
p = p.next;
}
ListNode nhead = p.next;
p.next = null;
return nhead;
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Remove Duplicate Letters(Java)]]></title>
<url>http://yoursite.com/2016/02/23/Leetcode-Remove-Duplicate-Letters-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.</p>
<p>Example:<br>Given “bcabc”<br>Return “abc”</p>
<p>Given “cbacdcbc”<br>Return “acdb”</p>
<p><strong>Thinking:</strong></p>
<p>Record the times characters emerges in the list and check from left to right.Record the smallest character postion of the list until find the unique character, then delete the bigger characters before smallest one and delete smallest from the rest of list.</p>
<p><strong>Solution:</strong></p>
<pre><code>public String removeDuplicateLetters(String s) {
int[] count = new int[26];
int smallest = 0;
if (s.length() == 0) return "";
for (char c: s.toCharArray()) count[c-'a']++;
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) < s.charAt(smallest)) smallest = i;
if (--count[s.charAt(i) - 'a'] == 0) break;
}
return s.charAt(smallest) + removeDuplicateLetters(s.substring(smallest+1).replaceAll(s.charAt(smallest)+"", ""));
}
</code></pre>]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Number of Digit One(Java)]]></title>
<url>http://yoursite.com/2016/02/23/Leetcode-Number-of-Digit-One-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.</p>
<p>For example:<br>Given n = 13,<br>Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.</p>
<p>Hint:</p>
<p>Beware of overflow.</p>
<p><strong>Thinking:</strong></p>
<p>This is question to find formula. We should notice that: </p>
<pre><code>1 1 [1, 9]
11 10 11 12 13 14 15 16 17 18 19 [10, 19]
1 21 [20, 29]
1 31 [30, 39]
1 41 [40, 49]
1 51 [50, 59]
1 61 [60, 69]
1 71 [70, 79]
1 81 [80, 89]
1 91 [90, 99]
11 100 101 102 103 104 105 106 107 108 109 [100, 109]
21 110 111 112 113 114 115 116 117 118 119 [110, 119]
11 120 121 122 123 124 125 126 127 128 129 [120, 129]
</code></pre><p>We should divide it into three situations in every digit division: one is bigger than 2, another is equal to 1 and the rest is less than 0. </p>
<p><strong>Solution:</strong></p>
<pre><code>public int countDigitOne(int n) {
int res = 0;
for (long m = 1; m <= n; m*=10) {
res += (n/m + 8) / 10 * m + (n/m % 10 == 1? n%m+1:0);
}
return res;
}
</code></pre><p>Reference: <a href="https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python" target="_blank" rel="external">https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python</a></p>
]]></content>
</entry>
<entry>
<title><![CDATA[Leetcode-Basic Calculator II(Java)]]></title>
<url>http://yoursite.com/2016/02/22/Leetcode-Basic-Calculator-II-Java/</url>
<content type="html"><![CDATA[<p><strong>Question:</strong></p>
<p>Implement a basic calculator to evaluate a simple expression string.</p>
<p>The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.</p>
<p>You may assume that the given expression is always valid.</p>
<p>Some examples:</p>
<pre><code>"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
</code></pre><p>Note: Do not use the eval built-in library function.</p>
<p><strong>Thinking:</strong></p>
<p>An efficient way to solve this problem is to use stack get last num for an operation. And in order to delay the operation after get the two numbers, we need a op variable to record the last op until find the second number. What’s more, accroding to their op, numbers push into the stack in different ways. Finnaly, we just need to get the element from stack and add them all.</p>