From f5630bff3d960d89db8779c6d74ce3253dd05894 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 6 Dec 2014 16:32:56 +0800 Subject: [PATCH 001/195] add new find peak element --- find-peak-element/README.md | 0 find-peak-element/Solution.java | 18 ++++++++++++++++++ find-peak-element/index.md | 8 ++++++++ 3 files changed, 26 insertions(+) create mode 100644 find-peak-element/README.md create mode 100644 find-peak-element/Solution.java create mode 100644 find-peak-element/index.md diff --git a/find-peak-element/README.md b/find-peak-element/README.md new file mode 100644 index 0000000..e69de29 diff --git a/find-peak-element/Solution.java b/find-peak-element/Solution.java new file mode 100644 index 0000000..7dfa2a5 --- /dev/null +++ b/find-peak-element/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + + int findPeakElement(int[] num, int from, int to) { + if(to - from == 1) return from; + + int m = (to + from) / 2; + + int l = findPeakElement(num, from, m); + int r = findPeakElement(num, m, to); + + if(num[l] > num[r]) return l; + else return r; + } + + public int findPeakElement(int[] num) { + return findPeakElement(num, 0, num.length); + } +} diff --git a/find-peak-element/index.md b/find-peak-element/index.md new file mode 100644 index 0000000..f8248e4 --- /dev/null +++ b/find-peak-element/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Find Peak Element +date: 2014-12-06 16:31:48+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From feef40e9d07f5cc9ba92fea008cd2472b912384d Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 6 Dec 2014 16:33:45 +0800 Subject: [PATCH 002/195] find peak ele solution to gh-pages --- _includes/_root/find-peak-element/README.md | 0 .../_root/find-peak-element/Solution.java | 18 ++++++++++++++++++ find-peak-element/index.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/find-peak-element/README.md create mode 100644 _includes/_root/find-peak-element/Solution.java diff --git a/_includes/_root/find-peak-element/README.md b/_includes/_root/find-peak-element/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/find-peak-element/Solution.java b/_includes/_root/find-peak-element/Solution.java new file mode 100644 index 0000000..7dfa2a5 --- /dev/null +++ b/_includes/_root/find-peak-element/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + + int findPeakElement(int[] num, int from, int to) { + if(to - from == 1) return from; + + int m = (to + from) / 2; + + int l = findPeakElement(num, from, m); + int r = findPeakElement(num, m, to); + + if(num[l] > num[r]) return l; + else return r; + } + + public int findPeakElement(int[] num) { + return findPeakElement(num, 0, num.length); + } +} diff --git a/find-peak-element/index.md b/find-peak-element/index.md index f8248e4..848cea8 100644 --- a/find-peak-element/index.md +++ b/find-peak-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Find Peak Element -date: 2014-12-06 16:31:48+08:00 +date: 2014-12-06 16:32:56 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From afd2dd0d4f902a75966f44a0f1bc83a1a7a62016 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 10 Dec 2014 19:09:28 +0800 Subject: [PATCH 003/195] add missing ranges --- missing-ranges/README.md | 0 missing-ranges/Solution.java | 52 ++++++++++++++++++++++++++++++++++++ missing-ranges/index.md | 8 ++++++ 3 files changed, 60 insertions(+) create mode 100644 missing-ranges/README.md create mode 100644 missing-ranges/Solution.java create mode 100644 missing-ranges/index.md diff --git a/missing-ranges/README.md b/missing-ranges/README.md new file mode 100644 index 0000000..e69de29 diff --git a/missing-ranges/Solution.java b/missing-ranges/Solution.java new file mode 100644 index 0000000..32511ad --- /dev/null +++ b/missing-ranges/Solution.java @@ -0,0 +1,52 @@ +public class Solution { + + static class Range { + int start; + int end; + + Range(int start, int end){ + this.start = start; + this.end = end; + } + + public String toString(){ + if(start == end) return "" + start; + + return start + "->" + end; + } + + boolean valid(){ + return end >= start; + } + + void addMeIfValid(List l){ + if(valid()){ + l.add(toString()); + } + } + } + + public List findMissingRanges(int[] A, int lower, int upper) { + + List rt = new ArrayList(); + + Range current = new Range(lower, upper); + + for(int i = 0; i < A.length; i++){ + if(A[i] > current.end) break; + + if(A[i] >= current.start){ + Range r = new Range(current.start, A[i] - 1); + + r.addMeIfValid(rt); + + current.start = A[i] + 1; + } + + } + + current.addMeIfValid(rt); + + return rt; + } +} diff --git a/missing-ranges/index.md b/missing-ranges/index.md new file mode 100644 index 0000000..dc8bd63 --- /dev/null +++ b/missing-ranges/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Missing Ranges +date: 2014-12-10 19:08:03+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 971acfd96aa130557a5a1acab741db7600e684e7 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 10 Dec 2014 19:11:26 +0800 Subject: [PATCH 004/195] add missing ranges to gh-pages --- _includes/_root/missing-ranges/README.md | 0 _includes/_root/missing-ranges/Solution.java | 52 ++++++++++++++++++++ missing-ranges/index.md | 2 +- 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/missing-ranges/README.md create mode 100644 _includes/_root/missing-ranges/Solution.java diff --git a/_includes/_root/missing-ranges/README.md b/_includes/_root/missing-ranges/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/missing-ranges/Solution.java b/_includes/_root/missing-ranges/Solution.java new file mode 100644 index 0000000..32511ad --- /dev/null +++ b/_includes/_root/missing-ranges/Solution.java @@ -0,0 +1,52 @@ +public class Solution { + + static class Range { + int start; + int end; + + Range(int start, int end){ + this.start = start; + this.end = end; + } + + public String toString(){ + if(start == end) return "" + start; + + return start + "->" + end; + } + + boolean valid(){ + return end >= start; + } + + void addMeIfValid(List l){ + if(valid()){ + l.add(toString()); + } + } + } + + public List findMissingRanges(int[] A, int lower, int upper) { + + List rt = new ArrayList(); + + Range current = new Range(lower, upper); + + for(int i = 0; i < A.length; i++){ + if(A[i] > current.end) break; + + if(A[i] >= current.start){ + Range r = new Range(current.start, A[i] - 1); + + r.addMeIfValid(rt); + + current.start = A[i] + 1; + } + + } + + current.addMeIfValid(rt); + + return rt; + } +} diff --git a/missing-ranges/index.md b/missing-ranges/index.md index dc8bd63..797da85 100644 --- a/missing-ranges/index.md +++ b/missing-ranges/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Missing Ranges -date: 2014-12-10 19:08:03+08:00 +date: 2014-12-10 19:09:28 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 603c1941ed238eae370521045d1605047ebc6085 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 01:41:01 +0800 Subject: [PATCH 005/195] max gap a bit hard --- maximum-gap/README.md | 0 maximum-gap/Solution.java | 69 +++++++++++++++++++++++++++++++++++++++ maximum-gap/index.md | 8 +++++ 3 files changed, 77 insertions(+) create mode 100644 maximum-gap/README.md create mode 100644 maximum-gap/Solution.java create mode 100644 maximum-gap/index.md diff --git a/maximum-gap/README.md b/maximum-gap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/maximum-gap/Solution.java b/maximum-gap/Solution.java new file mode 100644 index 0000000..80217ce --- /dev/null +++ b/maximum-gap/Solution.java @@ -0,0 +1,69 @@ +public class Solution { + + static class Bucket { + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + + int[] nums = new int[0]; + + void add(int n){ + min = Math.min(n, min); + max = Math.max(n, max); + + + nums = Arrays.copyOf(nums, nums.length + 1); + + nums[nums.length - 1] = n; + } + + int gap(){ + if (nums.length == 1) return 0; + if (nums.length == 2) return max - min; + + // bad case + Arrays.sort(nums); + + int g = nums[1] - nums[0]; + for(int i = 2; i < nums.length; i++){ + g = Math.max(nums[i] - nums[i - 1], g); + } + + return g; + } + } + + public int maximumGap(int[] num) { + if (num.length < 2) return 0; + + double _avg = num[0]; + + for(int i = 0; i < num.length; i++){ + _avg += (num[i] - _avg) / (i + 1); + } + + int avg = (int) Math.ceil(_avg); + + Bucket[] buckets = new Bucket[num.length]; + for(int i = 0; i < num.length; i++){ + int index = num[i] / avg; + + if(buckets[index] == null) buckets[index] = new Bucket(); + + buckets[index].add(num[i]); + } + + int gap = Integer.MIN_VALUE; + + if (buckets[0] != null) gap = buckets[0].gap(); + + for(int i = 1; i < buckets.length; i++){ + if(buckets[i] == null) continue; + gap = Math.max(gap, buckets[i].gap()); + + if(buckets[i - 1] == null) continue; + gap = Math.max(gap, buckets[i].min - buckets[i - 1].max); + } + + return gap; + } +} diff --git a/maximum-gap/index.md b/maximum-gap/index.md new file mode 100644 index 0000000..b943b30 --- /dev/null +++ b/maximum-gap/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Maximum Gap +date: 2014-12-15 01:37:44+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 55833f12238daffdd9f34dc7f48db8b4da4a3202 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 01:41:50 +0800 Subject: [PATCH 006/195] commit max gap to gh-pages --- _includes/_root/maximum-gap/README.md | 0 _includes/_root/maximum-gap/Solution.java | 69 +++++++++++++++++++++++ maximum-gap/index.md | 2 +- 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/maximum-gap/README.md create mode 100644 _includes/_root/maximum-gap/Solution.java diff --git a/_includes/_root/maximum-gap/README.md b/_includes/_root/maximum-gap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/maximum-gap/Solution.java b/_includes/_root/maximum-gap/Solution.java new file mode 100644 index 0000000..80217ce --- /dev/null +++ b/_includes/_root/maximum-gap/Solution.java @@ -0,0 +1,69 @@ +public class Solution { + + static class Bucket { + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + + int[] nums = new int[0]; + + void add(int n){ + min = Math.min(n, min); + max = Math.max(n, max); + + + nums = Arrays.copyOf(nums, nums.length + 1); + + nums[nums.length - 1] = n; + } + + int gap(){ + if (nums.length == 1) return 0; + if (nums.length == 2) return max - min; + + // bad case + Arrays.sort(nums); + + int g = nums[1] - nums[0]; + for(int i = 2; i < nums.length; i++){ + g = Math.max(nums[i] - nums[i - 1], g); + } + + return g; + } + } + + public int maximumGap(int[] num) { + if (num.length < 2) return 0; + + double _avg = num[0]; + + for(int i = 0; i < num.length; i++){ + _avg += (num[i] - _avg) / (i + 1); + } + + int avg = (int) Math.ceil(_avg); + + Bucket[] buckets = new Bucket[num.length]; + for(int i = 0; i < num.length; i++){ + int index = num[i] / avg; + + if(buckets[index] == null) buckets[index] = new Bucket(); + + buckets[index].add(num[i]); + } + + int gap = Integer.MIN_VALUE; + + if (buckets[0] != null) gap = buckets[0].gap(); + + for(int i = 1; i < buckets.length; i++){ + if(buckets[i] == null) continue; + gap = Math.max(gap, buckets[i].gap()); + + if(buckets[i - 1] == null) continue; + gap = Math.max(gap, buckets[i].min - buckets[i - 1].max); + } + + return gap; + } +} diff --git a/maximum-gap/index.md b/maximum-gap/index.md index b943b30..41e3ad7 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Gap -date: 2014-12-15 01:37:44+08:00 +date: 2014-12-15 01:41:01 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 0a76f9ff431cf52d0f642ff9f831a295f7fa1d55 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 02:25:44 +0800 Subject: [PATCH 007/195] shameless update after read leetcode solution --- maximum-gap/Solution.java | 51 +++++++++++++-------------------------- 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/maximum-gap/Solution.java b/maximum-gap/Solution.java index 80217ce..4f0498d 100644 --- a/maximum-gap/Solution.java +++ b/maximum-gap/Solution.java @@ -4,66 +4,49 @@ static class Bucket { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; - int[] nums = new int[0]; - void add(int n){ min = Math.min(n, min); max = Math.max(n, max); - - - nums = Arrays.copyOf(nums, nums.length + 1); - - nums[nums.length - 1] = n; - } - - int gap(){ - if (nums.length == 1) return 0; - if (nums.length == 2) return max - min; - - // bad case - Arrays.sort(nums); - - int g = nums[1] - nums[0]; - for(int i = 2; i < nums.length; i++){ - g = Math.max(nums[i] - nums[i - 1], g); - } - - return g; } } public int maximumGap(int[] num) { if (num.length < 2) return 0; - double _avg = num[0]; + int max = Integer.MIN_VALUE; + int min = Integer.MAX_VALUE; for(int i = 0; i < num.length; i++){ - _avg += (num[i] - _avg) / (i + 1); + max = Math.max(max, num[i]); + min = Math.min(min, num[i]); } - int avg = (int) Math.ceil(_avg); - Bucket[] buckets = new Bucket[num.length]; + int gap = (int) Math.ceil((double)(max - min) / (num.length - 1)); + int n = (max - min) / gap + 1; + + Bucket[] buckets = new Bucket[n]; + for(int i = 0; i < num.length; i++){ - int index = num[i] / avg; + int index = (num[i] - min) / gap; if(buckets[index] == null) buckets[index] = new Bucket(); buckets[index].add(num[i]); } - int gap = Integer.MIN_VALUE; + int maxGap = Integer.MIN_VALUE; - if (buckets[0] != null) gap = buckets[0].gap(); + int prev = min; - for(int i = 1; i < buckets.length; i++){ + for(int i = 0; i < buckets.length; i++){ if(buckets[i] == null) continue; - gap = Math.max(gap, buckets[i].gap()); - if(buckets[i - 1] == null) continue; - gap = Math.max(gap, buckets[i].min - buckets[i - 1].max); + maxGap = Math.max(maxGap, buckets[i].min - prev); + + prev = buckets[i].max; } - return gap; + return maxGap; } } From 10270b7822951456a54ba1f0b779674a5571e07e Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 02:26:25 +0800 Subject: [PATCH 008/195] commit max gap to gh-pages --- _includes/_root/maximum-gap/Solution.java | 51 ++++++++--------------- maximum-gap/index.md | 2 +- 2 files changed, 18 insertions(+), 35 deletions(-) diff --git a/_includes/_root/maximum-gap/Solution.java b/_includes/_root/maximum-gap/Solution.java index 80217ce..4f0498d 100644 --- a/_includes/_root/maximum-gap/Solution.java +++ b/_includes/_root/maximum-gap/Solution.java @@ -4,66 +4,49 @@ static class Bucket { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; - int[] nums = new int[0]; - void add(int n){ min = Math.min(n, min); max = Math.max(n, max); - - - nums = Arrays.copyOf(nums, nums.length + 1); - - nums[nums.length - 1] = n; - } - - int gap(){ - if (nums.length == 1) return 0; - if (nums.length == 2) return max - min; - - // bad case - Arrays.sort(nums); - - int g = nums[1] - nums[0]; - for(int i = 2; i < nums.length; i++){ - g = Math.max(nums[i] - nums[i - 1], g); - } - - return g; } } public int maximumGap(int[] num) { if (num.length < 2) return 0; - double _avg = num[0]; + int max = Integer.MIN_VALUE; + int min = Integer.MAX_VALUE; for(int i = 0; i < num.length; i++){ - _avg += (num[i] - _avg) / (i + 1); + max = Math.max(max, num[i]); + min = Math.min(min, num[i]); } - int avg = (int) Math.ceil(_avg); - Bucket[] buckets = new Bucket[num.length]; + int gap = (int) Math.ceil((double)(max - min) / (num.length - 1)); + int n = (max - min) / gap + 1; + + Bucket[] buckets = new Bucket[n]; + for(int i = 0; i < num.length; i++){ - int index = num[i] / avg; + int index = (num[i] - min) / gap; if(buckets[index] == null) buckets[index] = new Bucket(); buckets[index].add(num[i]); } - int gap = Integer.MIN_VALUE; + int maxGap = Integer.MIN_VALUE; - if (buckets[0] != null) gap = buckets[0].gap(); + int prev = min; - for(int i = 1; i < buckets.length; i++){ + for(int i = 0; i < buckets.length; i++){ if(buckets[i] == null) continue; - gap = Math.max(gap, buckets[i].gap()); - if(buckets[i - 1] == null) continue; - gap = Math.max(gap, buckets[i].min - buckets[i - 1].max); + maxGap = Math.max(maxGap, buckets[i].min - prev); + + prev = buckets[i].max; } - return gap; + return maxGap; } } diff --git a/maximum-gap/index.md b/maximum-gap/index.md index 41e3ad7..511d270 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Gap -date: 2014-12-15 01:41:01 +0800 +date: 2014-12-15 02:25:44 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 9191b073386a15127f1f85b258bbd338dceb28b5 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 17:18:30 +0800 Subject: [PATCH 009/195] add read n from read4 --- read-n-characters-given-read4/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/read-n-characters-given-read4/README.md b/read-n-characters-given-read4/README.md index e69de29..69203bc 100644 --- a/read-n-characters-given-read4/README.md +++ b/read-n-characters-given-read4/README.md @@ -0,0 +1,14 @@ +## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full + + +``` +.... .... .... ...E <- data read4 +++++ ++++ ++++ ++ <- data pipe to read +``` + +code should be like below + +``` +while not EOF or buf not full + append read4 to buf +``` From 1e3ab59fe1a374a3ca172a29eba0558bbd498d0c Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 17:32:05 +0800 Subject: [PATCH 010/195] add read from read4 ii doc --- .../README.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/read-n-characters-given-read4-ii-call-multiple-times/README.md b/read-n-characters-given-read4-ii-call-multiple-times/README.md index e69de29..5118d2e 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/README.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/README.md @@ -0,0 +1,23 @@ +## EAGAIN and read + +This is a common problem in real world. +when client read some data from server, data will not always be available to be read. +`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, +call me later. + +## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) + +when you call `read4`, it might return 4 `char`s. +however, the `read` only ask you for 1 `char`. +you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. + +to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. + +``` + | just store these two chars for coming read call + V + .... .... .... ..** .... .. +[++++ ++++ ++++ ++][ ++++ +] + +``` + From f51cf22d0591160a41b358c17355d255c1587f30 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 18:13:21 +0800 Subject: [PATCH 011/195] add doc for longest substring with at most distinct char --- .../README.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/longest-substring-with-at-most-two-distinct-characters/README.md b/longest-substring-with-at-most-two-distinct-characters/README.md index e69de29..7f82848 100644 --- a/longest-substring-with-at-most-two-distinct-characters/README.md +++ b/longest-substring-with-at-most-two-distinct-characters/README.md @@ -0,0 +1,36 @@ +## Relative of [Minimum Window Substring](../minimum-window-substring) + +This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). + +## Loop invariant + +Assume that `S` is a `string with at most two distinct char` + +when a new char `c` comes: + * append it to `S`'s right + * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` + +``` +S = 'aabb' + +new char c = 'c' + +S = 'aabbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'abbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'bbc' + +``` + + +## Finding max + +after each loop, `S` is a `string with at most two distinct char`. but, its length changes. +what we need is to find the max length. From fe0fce62eb549dc5f77c0b95b9d6c9f3cd5e140f Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 18:23:24 +0800 Subject: [PATCH 012/195] add doc for intersection of two list --- intersection-of-two-linked-lists/README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/intersection-of-two-linked-lists/README.md b/intersection-of-two-linked-lists/README.md index e69de29..3cd5882 100644 --- a/intersection-of-two-linked-lists/README.md +++ b/intersection-of-two-linked-lists/README.md @@ -0,0 +1,22 @@ +## Two Lists with same length + + +``` + +A: a1 → a2 + ↘ + c1 → c2 → c3 + ↗ +B: b1 → b2 + + +``` + +Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. + +## What if the length is not the same + +Make them the same. + + * find out two lists' length + * trim the longer one and remove the `overhead` From f0a9694a17d8fe449e9a3e193b5e75977d4dfae6 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 18:35:04 +0800 Subject: [PATCH 013/195] add doc for 1 edit distance --- one-edit-distance/README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/one-edit-distance/README.md b/one-edit-distance/README.md index e69de29..26004a9 100644 --- a/one-edit-distance/README.md +++ b/one-edit-distance/README.md @@ -0,0 +1,26 @@ +## [Edit Distance](../edit-distance) == 1 + +My first submission + + +``` +return minDistance(s, t) == 1; +``` + +but, leetcode shows `time limit exceeded`. + + +## Only 1 diff + +### Same length + +do one pass can know if there is only one different char + +### 1 char longer + +delete the redundant char will yield two same string + +Note: + +solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. + From 89b275b6195fbd78e61957cf1d73237e8036e0fb Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 15 Dec 2014 20:06:00 +0800 Subject: [PATCH 014/195] add find peak element doc --- find-peak-element/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/find-peak-element/README.md b/find-peak-element/README.md index e69de29..6df33e1 100644 --- a/find-peak-element/README.md +++ b/find-peak-element/README.md @@ -0,0 +1,11 @@ +## logarithmic is a sign + +`O(lg n)` is something like `binary search` or `merge sort`. + + +``` +find-peak-element = first elemen only one element + index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise +``` + + From c62f14691c0c4ebb9ed97149d8c0930b79f6e600 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 16 Dec 2014 00:23:40 +0800 Subject: [PATCH 015/195] add missing range doc --- missing-ranges/README.md | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/missing-ranges/README.md b/missing-ranges/README.md index e69de29..69aaf0c 100644 --- a/missing-ranges/README.md +++ b/missing-ranges/README.md @@ -0,0 +1,63 @@ +## Loop invariant + +init range is lower -> upper + +when a new number comes, the number divide the range into two ranges. +the left range must be a missing range. just output it. + + +``` +R = [0 -> 99] +S = [0, 1, 3, 50, 75] + ^ + | +``` + +`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` + +``` +R = [1 -> 99] +S = [1, 3, 50, 75] + ^ + | +``` + +`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` + +``` +R = [2 -> 99] +S = [3, 50, 75] + ^ + | +``` + +`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` + +`[2]` is a missing, output. + + +``` +R = [4 -> 99] +S = [50, 75] + ^ + | +``` + +`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` + +`[4 -> 49]` is a missing, output. + + +``` +R = [51 -> 99] +S = [75] + ^ + | +``` + +`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` + +`[51 -> 74]` is a missing, output. + + +the last one `[76 -> 99]` is a missing range too. From 786c75f5e74564acdb891e69866cd5d94befe5b9 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 16 Dec 2014 01:13:52 +0800 Subject: [PATCH 016/195] add max gap doc --- maximum-gap/README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/maximum-gap/README.md b/maximum-gap/README.md index e69de29..eb7dbb2 100644 --- a/maximum-gap/README.md +++ b/maximum-gap/README.md @@ -0,0 +1,32 @@ +## `O(n)` Sort + +The problem requires `O(n)` time complexity, and it looks something like sort. +[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) +are the two well known `O(n)` sort. + +Maybe an `O(32n)` radix sort will work well. + +## Bucket sort version + +> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. +Through, this solution got accepted by leetcode, I found there is a better solution. + +the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, +the `maximum gap` must be greater than `(max - min) / (N - 1)`. + +Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, +but, this time a good news is that we do not need to sort the numbers in the buckets, +what we need is only to remember the max and min of the bucket. +The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. + +after bucketing, numbers are like + +``` +[MIN] [MIN] [MIN] +[ ] [ ] ... [ ] +[MAX] [MAX] [MAX] +``` + +The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. + +Note: the will be some emtpy buckets, skip them. From e99793686c96e8c1f08eb6c419c66f3735d4533e Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 16 Dec 2014 01:15:17 +0800 Subject: [PATCH 017/195] push new docs into gh-pages --- _includes/_root/find-peak-element/README.md | 11 ++++ .../README.md | 22 +++++++ .../README.md | 36 +++++++++++ _includes/_root/maximum-gap/README.md | 32 ++++++++++ _includes/_root/missing-ranges/README.md | 63 +++++++++++++++++++ _includes/_root/one-edit-distance/README.md | 26 ++++++++ .../README.md | 23 +++++++ .../read-n-characters-given-read4/README.md | 14 +++++ find-peak-element/index.md | 2 +- intersection-of-two-linked-lists/index.md | 2 +- .../index.md | 2 +- maximum-gap/index.md | 2 +- missing-ranges/index.md | 2 +- one-edit-distance/index.md | 2 +- .../index.md | 2 +- read-n-characters-given-read4/index.md | 2 +- 16 files changed, 235 insertions(+), 8 deletions(-) diff --git a/_includes/_root/find-peak-element/README.md b/_includes/_root/find-peak-element/README.md index e69de29..6df33e1 100644 --- a/_includes/_root/find-peak-element/README.md +++ b/_includes/_root/find-peak-element/README.md @@ -0,0 +1,11 @@ +## logarithmic is a sign + +`O(lg n)` is something like `binary search` or `merge sort`. + + +``` +find-peak-element = first elemen only one element + index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise +``` + + diff --git a/_includes/_root/intersection-of-two-linked-lists/README.md b/_includes/_root/intersection-of-two-linked-lists/README.md index e69de29..3cd5882 100644 --- a/_includes/_root/intersection-of-two-linked-lists/README.md +++ b/_includes/_root/intersection-of-two-linked-lists/README.md @@ -0,0 +1,22 @@ +## Two Lists with same length + + +``` + +A: a1 → a2 + ↘ + c1 → c2 → c3 + ↗ +B: b1 → b2 + + +``` + +Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. + +## What if the length is not the same + +Make them the same. + + * find out two lists' length + * trim the longer one and remove the `overhead` diff --git a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md index e69de29..7f82848 100644 --- a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md +++ b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md @@ -0,0 +1,36 @@ +## Relative of [Minimum Window Substring](../minimum-window-substring) + +This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). + +## Loop invariant + +Assume that `S` is a `string with at most two distinct char` + +when a new char `c` comes: + * append it to `S`'s right + * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` + +``` +S = 'aabb' + +new char c = 'c' + +S = 'aabbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'abbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'bbc' + +``` + + +## Finding max + +after each loop, `S` is a `string with at most two distinct char`. but, its length changes. +what we need is to find the max length. diff --git a/_includes/_root/maximum-gap/README.md b/_includes/_root/maximum-gap/README.md index e69de29..eb7dbb2 100644 --- a/_includes/_root/maximum-gap/README.md +++ b/_includes/_root/maximum-gap/README.md @@ -0,0 +1,32 @@ +## `O(n)` Sort + +The problem requires `O(n)` time complexity, and it looks something like sort. +[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) +are the two well known `O(n)` sort. + +Maybe an `O(32n)` radix sort will work well. + +## Bucket sort version + +> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. +Through, this solution got accepted by leetcode, I found there is a better solution. + +the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, +the `maximum gap` must be greater than `(max - min) / (N - 1)`. + +Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, +but, this time a good news is that we do not need to sort the numbers in the buckets, +what we need is only to remember the max and min of the bucket. +The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. + +after bucketing, numbers are like + +``` +[MIN] [MIN] [MIN] +[ ] [ ] ... [ ] +[MAX] [MAX] [MAX] +``` + +The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. + +Note: the will be some emtpy buckets, skip them. diff --git a/_includes/_root/missing-ranges/README.md b/_includes/_root/missing-ranges/README.md index e69de29..69aaf0c 100644 --- a/_includes/_root/missing-ranges/README.md +++ b/_includes/_root/missing-ranges/README.md @@ -0,0 +1,63 @@ +## Loop invariant + +init range is lower -> upper + +when a new number comes, the number divide the range into two ranges. +the left range must be a missing range. just output it. + + +``` +R = [0 -> 99] +S = [0, 1, 3, 50, 75] + ^ + | +``` + +`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` + +``` +R = [1 -> 99] +S = [1, 3, 50, 75] + ^ + | +``` + +`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` + +``` +R = [2 -> 99] +S = [3, 50, 75] + ^ + | +``` + +`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` + +`[2]` is a missing, output. + + +``` +R = [4 -> 99] +S = [50, 75] + ^ + | +``` + +`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` + +`[4 -> 49]` is a missing, output. + + +``` +R = [51 -> 99] +S = [75] + ^ + | +``` + +`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` + +`[51 -> 74]` is a missing, output. + + +the last one `[76 -> 99]` is a missing range too. diff --git a/_includes/_root/one-edit-distance/README.md b/_includes/_root/one-edit-distance/README.md index e69de29..26004a9 100644 --- a/_includes/_root/one-edit-distance/README.md +++ b/_includes/_root/one-edit-distance/README.md @@ -0,0 +1,26 @@ +## [Edit Distance](../edit-distance) == 1 + +My first submission + + +``` +return minDistance(s, t) == 1; +``` + +but, leetcode shows `time limit exceeded`. + + +## Only 1 diff + +### Same length + +do one pass can know if there is only one different char + +### 1 char longer + +delete the redundant char will yield two same string + +Note: + +solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. + diff --git a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md index e69de29..5118d2e 100644 --- a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md +++ b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md @@ -0,0 +1,23 @@ +## EAGAIN and read + +This is a common problem in real world. +when client read some data from server, data will not always be available to be read. +`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, +call me later. + +## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) + +when you call `read4`, it might return 4 `char`s. +however, the `read` only ask you for 1 `char`. +you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. + +to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. + +``` + | just store these two chars for coming read call + V + .... .... .... ..** .... .. +[++++ ++++ ++++ ++][ ++++ +] + +``` + diff --git a/_includes/_root/read-n-characters-given-read4/README.md b/_includes/_root/read-n-characters-given-read4/README.md index e69de29..69203bc 100644 --- a/_includes/_root/read-n-characters-given-read4/README.md +++ b/_includes/_root/read-n-characters-given-read4/README.md @@ -0,0 +1,14 @@ +## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full + + +``` +.... .... .... ...E <- data read4 +++++ ++++ ++++ ++ <- data pipe to read +``` + +code should be like below + +``` +while not EOF or buf not full + append read4 to buf +``` diff --git a/find-peak-element/index.md b/find-peak-element/index.md index 848cea8..d639dcc 100644 --- a/find-peak-element/index.md +++ b/find-peak-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Find Peak Element -date: 2014-12-06 16:32:56 +0800 +date: 2014-12-15 20:06:00 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/intersection-of-two-linked-lists/index.md b/intersection-of-two-linked-lists/index.md index 2bdd9b1..c6e8731 100644 --- a/intersection-of-two-linked-lists/index.md +++ b/intersection-of-two-linked-lists/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Intersection of Two Linked Lists -date: 2014-12-02 13:09:51 +0800 +date: 2014-12-15 18:23:24 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-substring-with-at-most-two-distinct-characters/index.md b/longest-substring-with-at-most-two-distinct-characters/index.md index fe5f34b..0a81a0d 100644 --- a/longest-substring-with-at-most-two-distinct-characters/index.md +++ b/longest-substring-with-at-most-two-distinct-characters/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Substring with At Most Two Distinct Characters -date: 2014-11-26 19:06:13 +0800 +date: 2014-12-15 18:13:21 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximum-gap/index.md b/maximum-gap/index.md index 511d270..9c1467b 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Gap -date: 2014-12-15 02:25:44 +0800 +date: 2014-12-16 01:13:52 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/missing-ranges/index.md b/missing-ranges/index.md index 797da85..56802a1 100644 --- a/missing-ranges/index.md +++ b/missing-ranges/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Missing Ranges -date: 2014-12-10 19:09:28 +0800 +date: 2014-12-16 00:23:40 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/one-edit-distance/index.md b/one-edit-distance/index.md index 9ec9b33..66b01f0 100644 --- a/one-edit-distance/index.md +++ b/one-edit-distance/index.md @@ -1,7 +1,7 @@ --- layout: solution title: One Edit Distance -date: 2014-12-03 00:47:41 +0800 +date: 2014-12-15 18:35:04 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/read-n-characters-given-read4-ii-call-multiple-times/index.md b/read-n-characters-given-read4-ii-call-multiple-times/index.md index c958c89..183cf7e 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/index.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Read N Characters Given Read4 II - Call multiple times -date: 2014-11-24 17:31:29 +0800 +date: 2014-12-15 17:32:05 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/read-n-characters-given-read4/index.md b/read-n-characters-given-read4/index.md index 7785a72..0ad520c 100644 --- a/read-n-characters-given-read4/index.md +++ b/read-n-characters-given-read4/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Read N Characters Given Read4 -date: 2014-11-20 15:13:54 +0800 +date: 2014-12-15 17:18:30 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From d894242f4b8de957684eace21bfa29c7f89e4ba4 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 17 Dec 2014 06:37:52 +0800 Subject: [PATCH 018/195] add compare ver --- compare-version-numbers/README.md | 0 compare-version-numbers/Solution.java | 48 +++++++++++++++++++++++++++ compare-version-numbers/index.md | 8 +++++ 3 files changed, 56 insertions(+) create mode 100644 compare-version-numbers/README.md create mode 100644 compare-version-numbers/Solution.java create mode 100644 compare-version-numbers/index.md diff --git a/compare-version-numbers/README.md b/compare-version-numbers/README.md new file mode 100644 index 0000000..e69de29 diff --git a/compare-version-numbers/Solution.java b/compare-version-numbers/Solution.java new file mode 100644 index 0000000..19d3360 --- /dev/null +++ b/compare-version-numbers/Solution.java @@ -0,0 +1,48 @@ +public class Solution { + + String padding(String s, int len){ + if(s == null) s = ""; + + char[] p = new char[len - s.length()]; + + Arrays.fill(p, '0'); + + return new String(p) + s; + } + + int len(String s){ + if(s == null) return 0; + return s.length(); + } + + public int compareVersion(String version1, String version2) { + String[] v1 = version1.split("\\."); + String[] v2 = version2.split("\\."); + + int m = Math.max(v1.length, v2.length); + + v1 = Arrays.copyOf(v1, m); + v2 = Arrays.copyOf(v2, m); + + for(int i = 0; i < m; i++){ + String s1 = v1[i]; + String s2 = v2[i]; + + int l = Math.max(len(s1), len(s2)); + + s1 = padding(s1, l); + s2 = padding(s2, l); + + for(int j = 0; j < l; j++){ + if(s1.charAt(j) > s2.charAt(j)){ + return 1; + }else if(s1.charAt(j) < s2.charAt(j)){ + return -1; + } + } + + } + + return 0; + } +} diff --git a/compare-version-numbers/index.md b/compare-version-numbers/index.md new file mode 100644 index 0000000..7dd0edc --- /dev/null +++ b/compare-version-numbers/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Compare Version Numbers +date: 2014-12-17 06:35:15+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 10def92fd1aad1c08eb02a455ce55e1c98a35a25 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 17 Dec 2014 06:40:20 +0800 Subject: [PATCH 019/195] add frac to recur dec --- fraction-to-recurring-decimal/README.md | 0 fraction-to-recurring-decimal/Solution.java | 55 +++++++++++++++++++++ fraction-to-recurring-decimal/index.md | 8 +++ 3 files changed, 63 insertions(+) create mode 100644 fraction-to-recurring-decimal/README.md create mode 100644 fraction-to-recurring-decimal/Solution.java create mode 100644 fraction-to-recurring-decimal/index.md diff --git a/fraction-to-recurring-decimal/README.md b/fraction-to-recurring-decimal/README.md new file mode 100644 index 0000000..e69de29 diff --git a/fraction-to-recurring-decimal/Solution.java b/fraction-to-recurring-decimal/Solution.java new file mode 100644 index 0000000..b845951 --- /dev/null +++ b/fraction-to-recurring-decimal/Solution.java @@ -0,0 +1,55 @@ +public class Solution { + + public String fractionToDecimal(int numerator, int denominator) { + + String sign = ""; + + if(Math.signum(numerator) * Math.signum(denominator) < 0){ + sign = "-"; + } + + // cheat ... + long _numerator = numerator; + + long quotient = _numerator / denominator; + + _numerator %= denominator; + _numerator *= 10; + + final String intPart = "" + Math.abs(quotient); + + Map mod = new HashMap(); + + int i = 0; + + StringBuilder sb = new StringBuilder(); + + while(_numerator != 0){ + quotient = Math.abs(_numerator / denominator); + + _numerator %= denominator; + + Integer start = mod.get(_numerator + "," + quotient); + + if(start != null){ + sb.insert(start, "("); + sb.append(")"); + break; + } + + sb.append(quotient); + + mod.put(_numerator + "," + quotient, i); + + _numerator *= 10; + i++; + } + + String fractionalPart = sb.toString(); + + if(!"".equals(fractionalPart)) fractionalPart = "." + fractionalPart; + + return sign + intPart + fractionalPart; + + } +} diff --git a/fraction-to-recurring-decimal/index.md b/fraction-to-recurring-decimal/index.md new file mode 100644 index 0000000..21d2be0 --- /dev/null +++ b/fraction-to-recurring-decimal/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Fraction to Recurring Decimal +date: 2014-12-17 06:38:45+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From b93c6b326d73016851c2b41c67e5328e0b1d8d83 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 17 Dec 2014 06:41:28 +0800 Subject: [PATCH 020/195] commit new 2 to gh-pages --- .../_root/compare-version-numbers/README.md | 0 .../compare-version-numbers/Solution.java | 48 ++++++++++++++++ .../fraction-to-recurring-decimal/README.md | 0 .../Solution.java | 55 +++++++++++++++++++ compare-version-numbers/index.md | 2 +- fraction-to-recurring-decimal/index.md | 2 +- 6 files changed, 105 insertions(+), 2 deletions(-) create mode 100644 _includes/_root/compare-version-numbers/README.md create mode 100644 _includes/_root/compare-version-numbers/Solution.java create mode 100644 _includes/_root/fraction-to-recurring-decimal/README.md create mode 100644 _includes/_root/fraction-to-recurring-decimal/Solution.java diff --git a/_includes/_root/compare-version-numbers/README.md b/_includes/_root/compare-version-numbers/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/compare-version-numbers/Solution.java b/_includes/_root/compare-version-numbers/Solution.java new file mode 100644 index 0000000..19d3360 --- /dev/null +++ b/_includes/_root/compare-version-numbers/Solution.java @@ -0,0 +1,48 @@ +public class Solution { + + String padding(String s, int len){ + if(s == null) s = ""; + + char[] p = new char[len - s.length()]; + + Arrays.fill(p, '0'); + + return new String(p) + s; + } + + int len(String s){ + if(s == null) return 0; + return s.length(); + } + + public int compareVersion(String version1, String version2) { + String[] v1 = version1.split("\\."); + String[] v2 = version2.split("\\."); + + int m = Math.max(v1.length, v2.length); + + v1 = Arrays.copyOf(v1, m); + v2 = Arrays.copyOf(v2, m); + + for(int i = 0; i < m; i++){ + String s1 = v1[i]; + String s2 = v2[i]; + + int l = Math.max(len(s1), len(s2)); + + s1 = padding(s1, l); + s2 = padding(s2, l); + + for(int j = 0; j < l; j++){ + if(s1.charAt(j) > s2.charAt(j)){ + return 1; + }else if(s1.charAt(j) < s2.charAt(j)){ + return -1; + } + } + + } + + return 0; + } +} diff --git a/_includes/_root/fraction-to-recurring-decimal/README.md b/_includes/_root/fraction-to-recurring-decimal/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/fraction-to-recurring-decimal/Solution.java b/_includes/_root/fraction-to-recurring-decimal/Solution.java new file mode 100644 index 0000000..b845951 --- /dev/null +++ b/_includes/_root/fraction-to-recurring-decimal/Solution.java @@ -0,0 +1,55 @@ +public class Solution { + + public String fractionToDecimal(int numerator, int denominator) { + + String sign = ""; + + if(Math.signum(numerator) * Math.signum(denominator) < 0){ + sign = "-"; + } + + // cheat ... + long _numerator = numerator; + + long quotient = _numerator / denominator; + + _numerator %= denominator; + _numerator *= 10; + + final String intPart = "" + Math.abs(quotient); + + Map mod = new HashMap(); + + int i = 0; + + StringBuilder sb = new StringBuilder(); + + while(_numerator != 0){ + quotient = Math.abs(_numerator / denominator); + + _numerator %= denominator; + + Integer start = mod.get(_numerator + "," + quotient); + + if(start != null){ + sb.insert(start, "("); + sb.append(")"); + break; + } + + sb.append(quotient); + + mod.put(_numerator + "," + quotient, i); + + _numerator *= 10; + i++; + } + + String fractionalPart = sb.toString(); + + if(!"".equals(fractionalPart)) fractionalPart = "." + fractionalPart; + + return sign + intPart + fractionalPart; + + } +} diff --git a/compare-version-numbers/index.md b/compare-version-numbers/index.md index 7dd0edc..4f854fd 100644 --- a/compare-version-numbers/index.md +++ b/compare-version-numbers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Compare Version Numbers -date: 2014-12-17 06:35:15+08:00 +date: 2014-12-17 06:37:52 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/fraction-to-recurring-decimal/index.md b/fraction-to-recurring-decimal/index.md index 21d2be0..b513c0f 100644 --- a/fraction-to-recurring-decimal/index.md +++ b/fraction-to-recurring-decimal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Fraction to Recurring Decimal -date: 2014-12-17 06:38:45+08:00 +date: 2014-12-17 06:40:20 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 0a4ef692d1e248270ddd391e0a37598d92268704 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 20 Dec 2014 23:39:15 +0800 Subject: [PATCH 021/195] add two sum ii and excel sheet name --- excel-sheet-column-title/README.md | 0 excel-sheet-column-title/Solution.java | 13 ++++++++++++ excel-sheet-column-title/index.md | 8 ++++++++ two-sum-ii-input-array-is-sorted/README.md | 0 .../Solution.java | 20 +++++++++++++++++++ two-sum-ii-input-array-is-sorted/index.md | 8 ++++++++ 6 files changed, 49 insertions(+) create mode 100644 excel-sheet-column-title/README.md create mode 100644 excel-sheet-column-title/Solution.java create mode 100644 excel-sheet-column-title/index.md create mode 100644 two-sum-ii-input-array-is-sorted/README.md create mode 100644 two-sum-ii-input-array-is-sorted/Solution.java create mode 100644 two-sum-ii-input-array-is-sorted/index.md diff --git a/excel-sheet-column-title/README.md b/excel-sheet-column-title/README.md new file mode 100644 index 0000000..e69de29 diff --git a/excel-sheet-column-title/Solution.java b/excel-sheet-column-title/Solution.java new file mode 100644 index 0000000..c958d8f --- /dev/null +++ b/excel-sheet-column-title/Solution.java @@ -0,0 +1,13 @@ +public class Solution { + public String convertToTitle(int n) { + if(n < 27){ + return (char)('A' + (n - 1)) + ""; + } + + if( n % 26 == 0) { + return convertToTitle(n / 26 - 1) + 'Z'; + } + + return convertToTitle(n / 26) + convertToTitle(n % 26); + } +} diff --git a/excel-sheet-column-title/index.md b/excel-sheet-column-title/index.md new file mode 100644 index 0000000..abdfd73 --- /dev/null +++ b/excel-sheet-column-title/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Excel Sheet Column Title +date: 2014-12-20 23:37:45+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} diff --git a/two-sum-ii-input-array-is-sorted/README.md b/two-sum-ii-input-array-is-sorted/README.md new file mode 100644 index 0000000..e69de29 diff --git a/two-sum-ii-input-array-is-sorted/Solution.java b/two-sum-ii-input-array-is-sorted/Solution.java new file mode 100644 index 0000000..bb641c2 --- /dev/null +++ b/two-sum-ii-input-array-is-sorted/Solution.java @@ -0,0 +1,20 @@ +public class Solution { + public int[] twoSum(int[] numbers, int target) { + + int i = 0; + int j = numbers.length - 1; + + + while(i < j){ + if (numbers[i] + numbers[j] > target){ + j--; + }else if(numbers[i] + numbers[j] < target){ + i++; + }else { // == + return new int[]{i + 1, j + 1}; + } + } + + throw new RuntimeException(); + } +} diff --git a/two-sum-ii-input-array-is-sorted/index.md b/two-sum-ii-input-array-is-sorted/index.md new file mode 100644 index 0000000..4d91a74 --- /dev/null +++ b/two-sum-ii-input-array-is-sorted/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Two Sum II - Input array is sorted +date: 2014-12-20 23:36:49+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 673f95d6727fe5f95a679ab01ab84c9389454799 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 20 Dec 2014 23:40:52 +0800 Subject: [PATCH 022/195] two sum ii and excel sheet column title to gh-pages --- .../_root/excel-sheet-column-title/README.md | 0 .../excel-sheet-column-title/Solution.java | 13 ++++++++++++ .../README.md | 0 .../Solution.java | 20 +++++++++++++++++++ excel-sheet-column-title/index.md | 2 +- two-sum-ii-input-array-is-sorted/index.md | 2 +- 6 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 _includes/_root/excel-sheet-column-title/README.md create mode 100644 _includes/_root/excel-sheet-column-title/Solution.java create mode 100644 _includes/_root/two-sum-ii-input-array-is-sorted/README.md create mode 100644 _includes/_root/two-sum-ii-input-array-is-sorted/Solution.java diff --git a/_includes/_root/excel-sheet-column-title/README.md b/_includes/_root/excel-sheet-column-title/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/excel-sheet-column-title/Solution.java b/_includes/_root/excel-sheet-column-title/Solution.java new file mode 100644 index 0000000..c958d8f --- /dev/null +++ b/_includes/_root/excel-sheet-column-title/Solution.java @@ -0,0 +1,13 @@ +public class Solution { + public String convertToTitle(int n) { + if(n < 27){ + return (char)('A' + (n - 1)) + ""; + } + + if( n % 26 == 0) { + return convertToTitle(n / 26 - 1) + 'Z'; + } + + return convertToTitle(n / 26) + convertToTitle(n % 26); + } +} diff --git a/_includes/_root/two-sum-ii-input-array-is-sorted/README.md b/_includes/_root/two-sum-ii-input-array-is-sorted/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java b/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java new file mode 100644 index 0000000..bb641c2 --- /dev/null +++ b/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java @@ -0,0 +1,20 @@ +public class Solution { + public int[] twoSum(int[] numbers, int target) { + + int i = 0; + int j = numbers.length - 1; + + + while(i < j){ + if (numbers[i] + numbers[j] > target){ + j--; + }else if(numbers[i] + numbers[j] < target){ + i++; + }else { // == + return new int[]{i + 1, j + 1}; + } + } + + throw new RuntimeException(); + } +} diff --git a/excel-sheet-column-title/index.md b/excel-sheet-column-title/index.md index abdfd73..670fd9f 100644 --- a/excel-sheet-column-title/index.md +++ b/excel-sheet-column-title/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Excel Sheet Column Title -date: 2014-12-20 23:37:45+08:00 +date: 2014-12-20 23:39:15 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/two-sum-ii-input-array-is-sorted/index.md b/two-sum-ii-input-array-is-sorted/index.md index 4d91a74..8b1ea5d 100644 --- a/two-sum-ii-input-array-is-sorted/index.md +++ b/two-sum-ii-input-array-is-sorted/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum II - Input array is sorted -date: 2014-12-20 23:36:49+08:00 +date: 2014-12-20 23:39:15 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 2a2b2e9244078ad3e11be0aacdaaf22430fa1330 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 22 Dec 2014 15:14:45 +0800 Subject: [PATCH 023/195] add majority element --- majority-element/README.md | 0 majority-element/Solution.java | 18 ++++++++++++++++++ majority-element/index.md | 8 ++++++++ 3 files changed, 26 insertions(+) create mode 100644 majority-element/README.md create mode 100644 majority-element/Solution.java create mode 100644 majority-element/index.md diff --git a/majority-element/README.md b/majority-element/README.md new file mode 100644 index 0000000..e69de29 diff --git a/majority-element/Solution.java b/majority-element/Solution.java new file mode 100644 index 0000000..ea635a7 --- /dev/null +++ b/majority-element/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + public int majorityElement(int[] num) { + int m = num[0]; + int c = 1; + + for(int i = 1; i < num.length; i++){ + if(num[i] == m){ + c++; + }else if (c > 1){ + c--; + }else{ // c == 1 && num[i] != m + m = num[i]; + } + } + + return m; + } +} diff --git a/majority-element/index.md b/majority-element/index.md new file mode 100644 index 0000000..74abede --- /dev/null +++ b/majority-element/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Majority Element +date: 2014-12-22 15:13:37+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From c7e8401f4ed7446a2aab10655b3f7e1a15cd4d56 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 22 Dec 2014 15:16:09 +0800 Subject: [PATCH 024/195] add majority element --- _includes/_root/majority-element/README.md | 0 _includes/_root/majority-element/Solution.java | 18 ++++++++++++++++++ majority-element/index.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/majority-element/README.md create mode 100644 _includes/_root/majority-element/Solution.java diff --git a/_includes/_root/majority-element/README.md b/_includes/_root/majority-element/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/majority-element/Solution.java b/_includes/_root/majority-element/Solution.java new file mode 100644 index 0000000..ea635a7 --- /dev/null +++ b/_includes/_root/majority-element/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + public int majorityElement(int[] num) { + int m = num[0]; + int c = 1; + + for(int i = 1; i < num.length; i++){ + if(num[i] == m){ + c++; + }else if (c > 1){ + c--; + }else{ // c == 1 && num[i] != m + m = num[i]; + } + } + + return m; + } +} diff --git a/majority-element/index.md b/majority-element/index.md index 74abede..a8e735d 100644 --- a/majority-element/index.md +++ b/majority-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Majority Element -date: 2014-12-22 15:13:37+08:00 +date: 2014-12-22 15:14:45 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From f6060b78b92c224241e44bf40b1055f952caad02 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 26 Dec 2014 18:08:59 +0800 Subject: [PATCH 025/195] add two sum iii --- two-sum-iii-data-structure-design/README.md | 0 .../Solution.java | 32 +++++++++++++++++++ two-sum-iii-data-structure-design/TwoSum.java | 1 + two-sum-iii-data-structure-design/index.md | 8 +++++ 4 files changed, 41 insertions(+) create mode 100644 two-sum-iii-data-structure-design/README.md create mode 100644 two-sum-iii-data-structure-design/Solution.java create mode 120000 two-sum-iii-data-structure-design/TwoSum.java create mode 100644 two-sum-iii-data-structure-design/index.md diff --git a/two-sum-iii-data-structure-design/README.md b/two-sum-iii-data-structure-design/README.md new file mode 100644 index 0000000..e69de29 diff --git a/two-sum-iii-data-structure-design/Solution.java b/two-sum-iii-data-structure-design/Solution.java new file mode 100644 index 0000000..b8a7f47 --- /dev/null +++ b/two-sum-iii-data-structure-design/Solution.java @@ -0,0 +1,32 @@ +public class TwoSum { + + Map nums = new HashMap(); + + public void add(int number) { + Integer c = nums.get(number); + if(c == null) c = 0; + c++; + + nums.put(number, c); + } + + public boolean find(int value) { + + for(Integer n : nums.keySet()){ + Integer c = nums.get(value - n); + + if(c == null) continue; + + if(value - n == n){ + if(c > 1){ + return true; + } + }else{ + return true; + } + } + + + return false; + } +} diff --git a/two-sum-iii-data-structure-design/TwoSum.java b/two-sum-iii-data-structure-design/TwoSum.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/two-sum-iii-data-structure-design/TwoSum.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/two-sum-iii-data-structure-design/index.md b/two-sum-iii-data-structure-design/index.md new file mode 100644 index 0000000..90e44a0 --- /dev/null +++ b/two-sum-iii-data-structure-design/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Two Sum III - Data structure design +date: 2014-12-26 18:07:43+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 4fffc850725c3e191f129ba8bde6dd71f15ba907 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 26 Dec 2014 18:09:26 +0800 Subject: [PATCH 026/195] add two sum iii --- .../README.md | 0 .../Solution.java | 32 +++++++++++++++++++ two-sum-iii-data-structure-design/index.md | 2 +- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/two-sum-iii-data-structure-design/README.md create mode 100644 _includes/_root/two-sum-iii-data-structure-design/Solution.java diff --git a/_includes/_root/two-sum-iii-data-structure-design/README.md b/_includes/_root/two-sum-iii-data-structure-design/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/two-sum-iii-data-structure-design/Solution.java b/_includes/_root/two-sum-iii-data-structure-design/Solution.java new file mode 100644 index 0000000..b8a7f47 --- /dev/null +++ b/_includes/_root/two-sum-iii-data-structure-design/Solution.java @@ -0,0 +1,32 @@ +public class TwoSum { + + Map nums = new HashMap(); + + public void add(int number) { + Integer c = nums.get(number); + if(c == null) c = 0; + c++; + + nums.put(number, c); + } + + public boolean find(int value) { + + for(Integer n : nums.keySet()){ + Integer c = nums.get(value - n); + + if(c == null) continue; + + if(value - n == n){ + if(c > 1){ + return true; + } + }else{ + return true; + } + } + + + return false; + } +} diff --git a/two-sum-iii-data-structure-design/index.md b/two-sum-iii-data-structure-design/index.md index 90e44a0..e7041ba 100644 --- a/two-sum-iii-data-structure-design/index.md +++ b/two-sum-iii-data-structure-design/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum III - Data structure design -date: 2014-12-26 18:07:43+08:00 +date: 2014-12-26 18:08:59 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From feb1d1626c989eb6945a8c4d4ebea2a18bac47b3 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 28 Dec 2014 23:11:22 +0800 Subject: [PATCH 027/195] add excel sheet column number --- excel-sheet-column-number/README.md | 0 excel-sheet-column-number/Solution.java | 18 ++++++++++++++++++ excel-sheet-column-number/index.md | 8 ++++++++ 3 files changed, 26 insertions(+) create mode 100644 excel-sheet-column-number/README.md create mode 100644 excel-sheet-column-number/Solution.java create mode 100644 excel-sheet-column-number/index.md diff --git a/excel-sheet-column-number/README.md b/excel-sheet-column-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/excel-sheet-column-number/Solution.java b/excel-sheet-column-number/Solution.java new file mode 100644 index 0000000..befc36d --- /dev/null +++ b/excel-sheet-column-number/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + public int titleToNumber(String s) { + char[] S = s.toCharArray(); + + int n = 0; + + int p = 1; + + for(int i = S.length - 1; i >= 0; i--){ + + n += (S[i] - 'A' + 1) * p; + + p *= 26; + } + + return n; + } +} diff --git a/excel-sheet-column-number/index.md b/excel-sheet-column-number/index.md new file mode 100644 index 0000000..1909478 --- /dev/null +++ b/excel-sheet-column-number/index.md @@ -0,0 +1,8 @@ +--- +layout: solution +title: Excel Sheet Column Number +date: 2014-12-28 23:03:17+08:00 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From b7fef3f1ed3481b10cfb05c98a3b7c646bd27613 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 28 Dec 2014 23:13:21 +0800 Subject: [PATCH 028/195] add excel sheet column number to gh-pages --- .../_root/excel-sheet-column-number/README.md | 0 .../excel-sheet-column-number/Solution.java | 18 ++++++++++++++++++ excel-sheet-column-number/index.md | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/excel-sheet-column-number/README.md create mode 100644 _includes/_root/excel-sheet-column-number/Solution.java diff --git a/_includes/_root/excel-sheet-column-number/README.md b/_includes/_root/excel-sheet-column-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/excel-sheet-column-number/Solution.java b/_includes/_root/excel-sheet-column-number/Solution.java new file mode 100644 index 0000000..befc36d --- /dev/null +++ b/_includes/_root/excel-sheet-column-number/Solution.java @@ -0,0 +1,18 @@ +public class Solution { + public int titleToNumber(String s) { + char[] S = s.toCharArray(); + + int n = 0; + + int p = 1; + + for(int i = S.length - 1; i >= 0; i--){ + + n += (S[i] - 'A' + 1) * p; + + p *= 26; + } + + return n; + } +} diff --git a/excel-sheet-column-number/index.md b/excel-sheet-column-number/index.md index 1909478..404e0dc 100644 --- a/excel-sheet-column-number/index.md +++ b/excel-sheet-column-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Excel Sheet Column Number -date: 2014-12-28 23:03:17+08:00 +date: 2014-12-28 23:11:22 +0800 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} From 70b663fd007a3d5843fb76e24b70fc3970981059 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 29 Dec 2014 00:25:27 +0800 Subject: [PATCH 029/195] use leetcode_id for sorting --- 3sum-closest/index.md | 1 + 3sum/index.md | 1 + 4sum/index.md | 1 + add-binary/index.md | 1 + add-two-numbers/index.md | 1 + anagrams/index.md | 1 + balanced-binary-tree/index.md | 1 + best-time-to-buy-and-sell-stock-ii/index.md | 1 + best-time-to-buy-and-sell-stock-iii/index.md | 1 + best-time-to-buy-and-sell-stock/index.md | 1 + binary-tree-inorder-traversal/index.md | 1 + binary-tree-level-order-traversal-ii/index.md | 1 + binary-tree-level-order-traversal/index.md | 1 + binary-tree-maximum-path-sum/index.md | 1 + binary-tree-postorder-traversal/index.md | 1 + binary-tree-preorder-traversal/index.md | 1 + binary-tree-upside-down/index.md | 1 + binary-tree-zigzag-level-order-traversal/index.md | 1 + candy/index.md | 1 + climbing-stairs/index.md | 1 + clone-graph/index.md | 1 + combination-sum-ii/index.md | 1 + combination-sum/index.md | 1 + combinations/index.md | 1 + compare-version-numbers/index.md | 1 + .../index.md | 1 + .../index.md | 1 + container-with-most-water/index.md | 1 + convert-sorted-array-to-binary-search-tree/index.md | 1 + convert-sorted-list-to-binary-search-tree/index.md | 1 + copy-list-with-random-pointer/index.md | 1 + count-and-say/index.md | 1 + decode-ways/index.md | 1 + distinct-subsequences/index.md | 1 + divide-two-integers/index.md | 1 + edit-distance/index.md | 1 + evaluate-reverse-polish-notation/index.md | 1 + excel-sheet-column-number/index.md | 1 + excel-sheet-column-title/index.md | 1 + find-minimum-in-rotated-sorted-array-ii/index.md | 1 + find-minimum-in-rotated-sorted-array/index.md | 1 + find-peak-element/index.md | 1 + first-missing-positive/index.md | 1 + flatten-binary-tree-to-linked-list/index.md | 1 + fraction-to-recurring-decimal/index.md | 1 + gas-station/index.md | 1 + generate-parentheses/index.md | 1 + gray-code/index.md | 1 + implement-strstr/index.md | 1 + index.html | 4 ++-- insert-interval/index.md | 1 + insertion-sort-list/index.md | 1 + integer-to-roman/index.md | 1 + interleaving-string/index.md | 1 + intersection-of-two-linked-lists/index.md | 1 + jump-game-ii/index.md | 1 + jump-game/index.md | 1 + largest-rectangle-in-histogram/index.md | 1 + length-of-last-word/index.md | 1 + letter-combinations-of-a-phone-number/index.md | 1 + linked-list-cycle-ii/index.md | 1 + linked-list-cycle/index.md | 1 + longest-common-prefix/index.md | 1 + longest-consecutive-sequence/index.md | 1 + longest-palindromic-substring/index.md | 1 + .../index.md | 1 + longest-substring-without-repeating-characters/index.md | 1 + longest-valid-parentheses/index.md | 1 + lru-cache/index.md | 1 + majority-element/index.md | 1 + max-points-on-a-line/index.md | 1 + maximal-rectangle/index.md | 1 + maximum-depth-of-binary-tree/index.md | 1 + maximum-gap/index.md | 1 + maximum-product-subarray/index.md | 1 + maximum-subarray/index.md | 1 + median-of-two-sorted-arrays/index.md | 1 + merge-intervals/index.md | 1 + merge-k-sorted-lists/index.md | 1 + merge-sorted-array/index.md | 1 + merge-two-sorted-lists/index.md | 1 + min-stack/index.md | 1 + minimum-depth-of-binary-tree/index.md | 1 + minimum-path-sum/index.md | 1 + minimum-window-substring/index.md | 1 + missing-ranges/index.md | 1 + multiply-strings/index.md | 1 + n-queens-ii/index.md | 1 + n-queens/index.md | 1 + next-permutation/index.md | 1 + one-edit-distance/index.md | 1 + palindrome-number/index.md | 1 + palindrome-partitioning-ii/index.md | 1 + palindrome-partitioning/index.md | 1 + partition-list/index.md | 1 + pascals-triangle-ii/index.md | 1 + pascals-triangle/index.md | 1 + path-sum-ii/index.md | 1 + path-sum/index.md | 1 + permutation-sequence/index.md | 1 + permutations-ii/index.md | 1 + permutations/index.md | 1 + plus-one/index.md | 1 + populating-next-right-pointers-in-each-node-ii/index.md | 1 + populating-next-right-pointers-in-each-node/index.md | 1 + powx-n/index.md | 1 + read-n-characters-given-read4-ii-call-multiple-times/index.md | 1 + read-n-characters-given-read4/index.md | 1 + recover-binary-search-tree/index.md | 1 + regular-expression-matching/index.md | 1 + remove-duplicates-from-sorted-array-ii/index.md | 1 + remove-duplicates-from-sorted-array/index.md | 1 + remove-duplicates-from-sorted-list-ii/index.md | 1 + remove-duplicates-from-sorted-list/index.md | 1 + remove-element/index.md | 1 + remove-nth-node-from-end-of-list/index.md | 1 + reorder-list/index.md | 1 + restore-ip-addresses/index.md | 1 + reverse-integer/index.md | 1 + reverse-linked-list-ii/index.md | 1 + reverse-nodes-in-k-group/index.md | 1 + reverse-words-in-a-string/index.md | 1 + roman-to-integer/index.md | 1 + rotate-image/index.md | 1 + rotate-list/index.md | 1 + same-tree/index.md | 1 + scramble-string/index.md | 1 + search-a-2d-matrix/index.md | 1 + search-for-a-range/index.md | 1 + search-in-rotated-sorted-array-ii/index.md | 1 + search-in-rotated-sorted-array/index.md | 1 + search-insert-position/index.md | 1 + set-matrix-zeroes/index.md | 1 + simplify-path/index.md | 1 + single-number-ii/index.md | 1 + single-number/index.md | 1 + skeleton.sh | 1 + sort-colors/index.md | 1 + sort-list/index.md | 1 + spiral-matrix-ii/index.md | 1 + spiral-matrix/index.md | 1 + sqrtx/index.md | 1 + string-to-integer-atoi/index.md | 1 + subsets-ii/index.md | 1 + subsets/index.md | 1 + substring-with-concatenation-of-all-words/index.md | 1 + sudoku-solver/index.md | 1 + sum-root-to-leaf-numbers/index.md | 1 + surrounded-regions/index.md | 1 + swap-nodes-in-pairs/index.md | 1 + symmetric-tree/index.md | 1 + text-justification/index.md | 1 + trapping-rain-water/index.md | 1 + triangle/index.md | 1 + two-sum-ii-input-array-is-sorted/index.md | 1 + two-sum-iii-data-structure-design/index.md | 1 + two-sum/index.md | 2 ++ unique-binary-search-trees-ii/index.md | 1 + unique-binary-search-trees/index.md | 1 + unique-paths-ii/index.md | 1 + unique-paths/index.md | 1 + valid-number/index.md | 1 + valid-palindrome/index.md | 1 + valid-parentheses/index.md | 1 + valid-sudoku/index.md | 1 + validate-binary-search-tree/index.md | 1 + wildcard-matching/index.md | 1 + word-break-ii/index.md | 1 + word-break/index.md | 1 + word-ladder-ii/index.md | 1 + word-ladder/index.md | 1 + word-search/index.md | 1 + zigzag-conversion/index.md | 1 + 173 files changed, 175 insertions(+), 2 deletions(-) diff --git a/3sum-closest/index.md b/3sum-closest/index.md index cb89812..ab96981 100644 --- a/3sum-closest/index.md +++ b/3sum-closest/index.md @@ -2,6 +2,7 @@ layout: solution title: 3Sum Closest date: 2014-08-02 23:07:51 +0800 +leetcode_id: 16 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/3sum/index.md b/3sum/index.md index 9818ec9..2094319 100644 --- a/3sum/index.md +++ b/3sum/index.md @@ -2,6 +2,7 @@ layout: solution title: 3Sum date: 2014-08-02 23:02:32 +0800 +leetcode_id: 15 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/4sum/index.md b/4sum/index.md index 6d9580e..0129bf0 100644 --- a/4sum/index.md +++ b/4sum/index.md @@ -2,6 +2,7 @@ layout: solution title: 4Sum date: 2014-08-02 23:43:08 +0800 +leetcode_id: 18 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/add-binary/index.md b/add-binary/index.md index 039bc64..a6100c8 100644 --- a/add-binary/index.md +++ b/add-binary/index.md @@ -2,6 +2,7 @@ layout: solution title: Add Binary date: 2014-08-02 20:24:48 +0800 +leetcode_id: 67 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/add-two-numbers/index.md b/add-two-numbers/index.md index 9a52dcf..d534514 100644 --- a/add-two-numbers/index.md +++ b/add-two-numbers/index.md @@ -2,6 +2,7 @@ layout: solution title: Add Two Numbers date: 2014-08-02 20:31:49 +0800 +leetcode_id: 2 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/anagrams/index.md b/anagrams/index.md index 18b583d..242d1b7 100644 --- a/anagrams/index.md +++ b/anagrams/index.md @@ -2,6 +2,7 @@ layout: solution title: Anagrams date: 2014-07-26 18:47:25 +0800 +leetcode_id: 49 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/balanced-binary-tree/index.md b/balanced-binary-tree/index.md index b8b470f..4012030 100644 --- a/balanced-binary-tree/index.md +++ b/balanced-binary-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Balanced Binary Tree date: 2014-07-25 01:13:33 +0800 +leetcode_id: 110 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/best-time-to-buy-and-sell-stock-ii/index.md b/best-time-to-buy-and-sell-stock-ii/index.md index 4a9432e..df67efa 100644 --- a/best-time-to-buy-and-sell-stock-ii/index.md +++ b/best-time-to-buy-and-sell-stock-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Best Time to Buy and Sell Stock II date: 2014-07-30 23:47:55 +0800 +leetcode_id: 122 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/best-time-to-buy-and-sell-stock-iii/index.md b/best-time-to-buy-and-sell-stock-iii/index.md index 1e48594..bf69cc9 100644 --- a/best-time-to-buy-and-sell-stock-iii/index.md +++ b/best-time-to-buy-and-sell-stock-iii/index.md @@ -2,6 +2,7 @@ layout: solution title: Best Time to Buy and Sell Stock III date: 2014-08-03 08:26:32 +0800 +leetcode_id: 123 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/best-time-to-buy-and-sell-stock/index.md b/best-time-to-buy-and-sell-stock/index.md index 0132ce8..cfbb401 100644 --- a/best-time-to-buy-and-sell-stock/index.md +++ b/best-time-to-buy-and-sell-stock/index.md @@ -2,6 +2,7 @@ layout: solution title: Best Time to Buy and Sell Stock date: 2014-07-30 00:42:07 +0800 +leetcode_id: 121 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-inorder-traversal/index.md b/binary-tree-inorder-traversal/index.md index a77dbe9..3a1d9fd 100644 --- a/binary-tree-inorder-traversal/index.md +++ b/binary-tree-inorder-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Inorder Traversal date: 2014-07-28 01:06:09 +0800 +leetcode_id: 94 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-level-order-traversal-ii/index.md b/binary-tree-level-order-traversal-ii/index.md index a6e8cec..9e09530 100644 --- a/binary-tree-level-order-traversal-ii/index.md +++ b/binary-tree-level-order-traversal-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Level Order Traversal II date: 2014-08-01 19:04:31 +0800 +leetcode_id: 107 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-level-order-traversal/index.md b/binary-tree-level-order-traversal/index.md index dfee144..72fedf7 100644 --- a/binary-tree-level-order-traversal/index.md +++ b/binary-tree-level-order-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Level Order Traversal date: 2014-08-01 17:34:15 +0800 +leetcode_id: 102 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-maximum-path-sum/index.md b/binary-tree-maximum-path-sum/index.md index 7b8dbad..4f2df61 100644 --- a/binary-tree-maximum-path-sum/index.md +++ b/binary-tree-maximum-path-sum/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Maximum Path Sum date: 2014-08-12 18:28:08 +0800 +leetcode_id: 124 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-postorder-traversal/index.md b/binary-tree-postorder-traversal/index.md index ddb969f..b9714cb 100644 --- a/binary-tree-postorder-traversal/index.md +++ b/binary-tree-postorder-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Postorder Traversal date: 2014-07-30 01:19:00 +0800 +leetcode_id: 145 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-preorder-traversal/index.md b/binary-tree-preorder-traversal/index.md index 37b0d48..0db5728 100644 --- a/binary-tree-preorder-traversal/index.md +++ b/binary-tree-preorder-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Preorder Traversal date: 2014-07-30 01:18:02 +0800 +leetcode_id: 144 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-upside-down/index.md b/binary-tree-upside-down/index.md index 0331bf2..0e28334 100644 --- a/binary-tree-upside-down/index.md +++ b/binary-tree-upside-down/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Upside Down date: 2014-11-18 01:45:13 +0800 +leetcode_id: 156 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/binary-tree-zigzag-level-order-traversal/index.md b/binary-tree-zigzag-level-order-traversal/index.md index f6f3344..3786b46 100644 --- a/binary-tree-zigzag-level-order-traversal/index.md +++ b/binary-tree-zigzag-level-order-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Binary Tree Zigzag Level Order Traversal date: 2014-08-06 20:53:54 +0800 +leetcode_id: 103 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/candy/index.md b/candy/index.md index 87bbe8d..68c2224 100644 --- a/candy/index.md +++ b/candy/index.md @@ -2,6 +2,7 @@ layout: solution title: Candy date: 2014-08-01 14:53:22 +0800 +leetcode_id: 135 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/climbing-stairs/index.md b/climbing-stairs/index.md index 4402016..c16e4d7 100644 --- a/climbing-stairs/index.md +++ b/climbing-stairs/index.md @@ -2,6 +2,7 @@ layout: solution title: Climbing Stairs date: 2014-07-29 15:10:41 +0800 +leetcode_id: 70 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/clone-graph/index.md b/clone-graph/index.md index c5556dd..7eb9060 100644 --- a/clone-graph/index.md +++ b/clone-graph/index.md @@ -2,6 +2,7 @@ layout: solution title: Clone Graph date: 2014-07-25 18:53:55 +0800 +leetcode_id: 133 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/combination-sum-ii/index.md b/combination-sum-ii/index.md index ba8e8e4..de86bf4 100644 --- a/combination-sum-ii/index.md +++ b/combination-sum-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Combination Sum II date: 2014-08-13 18:00:07 +0800 +leetcode_id: 40 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/combination-sum/index.md b/combination-sum/index.md index aa5910d..9b9f9ea 100644 --- a/combination-sum/index.md +++ b/combination-sum/index.md @@ -2,6 +2,7 @@ layout: solution title: Combination Sum date: 2014-08-13 17:57:39 +0800 +leetcode_id: 39 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/combinations/index.md b/combinations/index.md index 47405e5..1ed4036 100644 --- a/combinations/index.md +++ b/combinations/index.md @@ -2,6 +2,7 @@ layout: solution title: Combinations date: 2014-08-07 22:09:22 +0800 +leetcode_id: 77 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/compare-version-numbers/index.md b/compare-version-numbers/index.md index 4f854fd..dccffb1 100644 --- a/compare-version-numbers/index.md +++ b/compare-version-numbers/index.md @@ -2,6 +2,7 @@ layout: solution title: Compare Version Numbers date: 2014-12-17 06:37:52 +0800 +leetcode_id: 165 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md index 49d2219..c644936 100644 --- a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md +++ b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Construct Binary Tree from Inorder and Postorder Traversal date: 2014-08-12 19:03:53 +0800 +leetcode_id: 106 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md index e6da53e..bced3c4 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md @@ -2,6 +2,7 @@ layout: solution title: Construct Binary Tree from Preorder and Inorder Traversal date: 2014-08-12 18:59:20 +0800 +leetcode_id: 105 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/container-with-most-water/index.md b/container-with-most-water/index.md index dbb40df..a9ee683 100644 --- a/container-with-most-water/index.md +++ b/container-with-most-water/index.md @@ -2,6 +2,7 @@ layout: solution title: Container With Most Water date: 2014-08-04 14:16:13 +0800 +leetcode_id: 11 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/convert-sorted-array-to-binary-search-tree/index.md b/convert-sorted-array-to-binary-search-tree/index.md index 295e213..aed8e38 100644 --- a/convert-sorted-array-to-binary-search-tree/index.md +++ b/convert-sorted-array-to-binary-search-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Convert Sorted Array to Binary Search Tree date: 2014-08-02 20:48:40 +0800 +leetcode_id: 108 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/convert-sorted-list-to-binary-search-tree/index.md b/convert-sorted-list-to-binary-search-tree/index.md index 7342dd6..65960aa 100644 --- a/convert-sorted-list-to-binary-search-tree/index.md +++ b/convert-sorted-list-to-binary-search-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Convert Sorted List to Binary Search Tree date: 2014-08-03 00:44:50 +0800 +leetcode_id: 109 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/copy-list-with-random-pointer/index.md b/copy-list-with-random-pointer/index.md index 57a847b..76495fe 100644 --- a/copy-list-with-random-pointer/index.md +++ b/copy-list-with-random-pointer/index.md @@ -2,6 +2,7 @@ layout: solution title: Copy List with Random Pointer date: 2014-08-01 18:11:42 +0800 +leetcode_id: 138 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/count-and-say/index.md b/count-and-say/index.md index cd4085b..ae9d2d7 100644 --- a/count-and-say/index.md +++ b/count-and-say/index.md @@ -2,6 +2,7 @@ layout: solution title: Count and Say date: 2014-07-26 18:50:47 +0800 +leetcode_id: 38 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/decode-ways/index.md b/decode-ways/index.md index 42370cf..6590566 100644 --- a/decode-ways/index.md +++ b/decode-ways/index.md @@ -2,6 +2,7 @@ layout: solution title: Decode Ways date: 2014-08-01 11:16:28 +0800 +leetcode_id: 91 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/distinct-subsequences/index.md b/distinct-subsequences/index.md index 27919dc..c6e7085 100644 --- a/distinct-subsequences/index.md +++ b/distinct-subsequences/index.md @@ -2,6 +2,7 @@ layout: solution title: Distinct Subsequences date: 2014-08-28 01:16:24 +0800 +leetcode_id: 115 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/divide-two-integers/index.md b/divide-two-integers/index.md index ae84b97..515497b 100644 --- a/divide-two-integers/index.md +++ b/divide-two-integers/index.md @@ -2,6 +2,7 @@ layout: solution title: Divide Two Integers date: 2014-07-26 22:51:51 +0800 +leetcode_id: 29 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/edit-distance/index.md b/edit-distance/index.md index 24207ed..8475748 100644 --- a/edit-distance/index.md +++ b/edit-distance/index.md @@ -2,6 +2,7 @@ layout: solution title: Edit Distance date: 2014-08-27 01:17:53 +0800 +leetcode_id: 72 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/evaluate-reverse-polish-notation/index.md b/evaluate-reverse-polish-notation/index.md index eedf316..19cdfc8 100644 --- a/evaluate-reverse-polish-notation/index.md +++ b/evaluate-reverse-polish-notation/index.md @@ -2,6 +2,7 @@ layout: solution title: Evaluate Reverse Polish Notation date: 2014-08-02 20:57:09 +0800 +leetcode_id: 150 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/excel-sheet-column-number/index.md b/excel-sheet-column-number/index.md index 404e0dc..4de8576 100644 --- a/excel-sheet-column-number/index.md +++ b/excel-sheet-column-number/index.md @@ -2,6 +2,7 @@ layout: solution title: Excel Sheet Column Number date: 2014-12-28 23:11:22 +0800 +leetcode_id: 171 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/excel-sheet-column-title/index.md b/excel-sheet-column-title/index.md index 670fd9f..584735a 100644 --- a/excel-sheet-column-title/index.md +++ b/excel-sheet-column-title/index.md @@ -2,6 +2,7 @@ layout: solution title: Excel Sheet Column Title date: 2014-12-20 23:39:15 +0800 +leetcode_id: 168 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/find-minimum-in-rotated-sorted-array-ii/index.md b/find-minimum-in-rotated-sorted-array-ii/index.md index ab8e6f5..a7191f6 100644 --- a/find-minimum-in-rotated-sorted-array-ii/index.md +++ b/find-minimum-in-rotated-sorted-array-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Find Minimum in Rotated Sorted Array II date: 2014-10-21 13:50:45 +0800 +leetcode_id: 154 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/find-minimum-in-rotated-sorted-array/index.md b/find-minimum-in-rotated-sorted-array/index.md index 47cefb2..93f9415 100644 --- a/find-minimum-in-rotated-sorted-array/index.md +++ b/find-minimum-in-rotated-sorted-array/index.md @@ -2,6 +2,7 @@ layout: solution title: Find Minimum in Rotated Sorted Array date: 2014-10-21 13:29:49 +0800 +leetcode_id: 153 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/find-peak-element/index.md b/find-peak-element/index.md index d639dcc..96b6acd 100644 --- a/find-peak-element/index.md +++ b/find-peak-element/index.md @@ -2,6 +2,7 @@ layout: solution title: Find Peak Element date: 2014-12-15 20:06:00 +0800 +leetcode_id: 162 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/first-missing-positive/index.md b/first-missing-positive/index.md index 02a6b09..2035908 100644 --- a/first-missing-positive/index.md +++ b/first-missing-positive/index.md @@ -2,6 +2,7 @@ layout: solution title: First Missing Positive date: 2014-08-04 12:45:58 +0800 +leetcode_id: 41 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/flatten-binary-tree-to-linked-list/index.md b/flatten-binary-tree-to-linked-list/index.md index 308d3c1..4700562 100644 --- a/flatten-binary-tree-to-linked-list/index.md +++ b/flatten-binary-tree-to-linked-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Flatten Binary Tree to Linked List date: 2014-08-04 13:46:49 +0800 +leetcode_id: 114 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/fraction-to-recurring-decimal/index.md b/fraction-to-recurring-decimal/index.md index b513c0f..9a58b04 100644 --- a/fraction-to-recurring-decimal/index.md +++ b/fraction-to-recurring-decimal/index.md @@ -2,6 +2,7 @@ layout: solution title: Fraction to Recurring Decimal date: 2014-12-17 06:40:20 +0800 +leetcode_id: 166 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/gas-station/index.md b/gas-station/index.md index be9aed8..0d6b5a8 100644 --- a/gas-station/index.md +++ b/gas-station/index.md @@ -2,6 +2,7 @@ layout: solution title: Gas Station date: 2014-08-17 23:57:14 +0800 +leetcode_id: 134 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/generate-parentheses/index.md b/generate-parentheses/index.md index a66d786..dc0386d 100644 --- a/generate-parentheses/index.md +++ b/generate-parentheses/index.md @@ -2,6 +2,7 @@ layout: solution title: Generate Parentheses date: 2014-08-12 16:58:24 +0800 +leetcode_id: 22 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/gray-code/index.md b/gray-code/index.md index 60c000a..1252617 100644 --- a/gray-code/index.md +++ b/gray-code/index.md @@ -2,6 +2,7 @@ layout: solution title: Gray Code date: 2014-08-07 20:12:44 +0800 +leetcode_id: 89 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/implement-strstr/index.md b/implement-strstr/index.md index ea283fb..c0a2fb9 100644 --- a/implement-strstr/index.md +++ b/implement-strstr/index.md @@ -2,6 +2,7 @@ layout: solution title: Implement strStr() date: 2014-07-24 23:50:24 +0800 +leetcode_id: 28 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/index.html b/index.html index 20b7341..3455eef 100644 --- a/index.html +++ b/index.html @@ -6,10 +6,10 @@

Solutions Last update on {{site.time}}

    - {% assign pages = site.pages | where: 'layout', 'solution' | sort: 'date' %} + {% assign pages = site.pages | where: 'layout', 'solution' | sort: 'leetcode_id' %} {% for page in pages reversed %}
  • - {{ page.title }} + {{page.leetcode_id}} {{ page.title }}
  • {% endfor %}
diff --git a/insert-interval/index.md b/insert-interval/index.md index d7cd15e..4d9e99b 100644 --- a/insert-interval/index.md +++ b/insert-interval/index.md @@ -2,6 +2,7 @@ layout: solution title: Insert Interval date: 2014-07-31 00:15:25 +0800 +leetcode_id: 57 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/insertion-sort-list/index.md b/insertion-sort-list/index.md index c45fd83..f7a1cc6 100644 --- a/insertion-sort-list/index.md +++ b/insertion-sort-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Insertion Sort List date: 2014-08-06 10:22:40 +0800 +leetcode_id: 147 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/integer-to-roman/index.md b/integer-to-roman/index.md index 0f46032..ea56551 100644 --- a/integer-to-roman/index.md +++ b/integer-to-roman/index.md @@ -2,6 +2,7 @@ layout: solution title: Integer to Roman date: 2014-08-07 17:11:23 +0800 +leetcode_id: 12 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/interleaving-string/index.md b/interleaving-string/index.md index 02dd3eb..8204a70 100644 --- a/interleaving-string/index.md +++ b/interleaving-string/index.md @@ -2,6 +2,7 @@ layout: solution title: Interleaving String date: 2014-08-06 11:48:41 +0800 +leetcode_id: 97 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/intersection-of-two-linked-lists/index.md b/intersection-of-two-linked-lists/index.md index c6e8731..1f950ae 100644 --- a/intersection-of-two-linked-lists/index.md +++ b/intersection-of-two-linked-lists/index.md @@ -2,6 +2,7 @@ layout: solution title: Intersection of Two Linked Lists date: 2014-12-15 18:23:24 +0800 +leetcode_id: 160 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/jump-game-ii/index.md b/jump-game-ii/index.md index 9265b3d..15409aa 100644 --- a/jump-game-ii/index.md +++ b/jump-game-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Jump Game II date: 2014-08-05 23:31:47 +0800 +leetcode_id: 45 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/jump-game/index.md b/jump-game/index.md index 40b9489..cc09a9d 100644 --- a/jump-game/index.md +++ b/jump-game/index.md @@ -2,6 +2,7 @@ layout: solution title: Jump Game date: 2014-07-23 18:48:31 +0800 +leetcode_id: 55 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/largest-rectangle-in-histogram/index.md b/largest-rectangle-in-histogram/index.md index 5023c0e..5eb25fd 100644 --- a/largest-rectangle-in-histogram/index.md +++ b/largest-rectangle-in-histogram/index.md @@ -2,6 +2,7 @@ layout: solution title: Largest Rectangle in Histogram date: 2014-07-30 17:01:27 +0800 +leetcode_id: 84 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/length-of-last-word/index.md b/length-of-last-word/index.md index 309f3a0..989eaea 100644 --- a/length-of-last-word/index.md +++ b/length-of-last-word/index.md @@ -2,6 +2,7 @@ layout: solution title: Length of Last Word date: 2014-08-04 14:46:58 +0800 +leetcode_id: 58 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/letter-combinations-of-a-phone-number/index.md b/letter-combinations-of-a-phone-number/index.md index 1e7882b..d59ebbd 100644 --- a/letter-combinations-of-a-phone-number/index.md +++ b/letter-combinations-of-a-phone-number/index.md @@ -2,6 +2,7 @@ layout: solution title: Letter Combinations of a Phone Number date: 2014-07-26 23:35:47 +0800 +leetcode_id: 17 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/linked-list-cycle-ii/index.md b/linked-list-cycle-ii/index.md index 9115a9c..7c63e2c 100644 --- a/linked-list-cycle-ii/index.md +++ b/linked-list-cycle-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Linked List Cycle II date: 2014-07-30 17:54:32 +0800 +leetcode_id: 142 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/linked-list-cycle/index.md b/linked-list-cycle/index.md index f34a614..9b61c53 100644 --- a/linked-list-cycle/index.md +++ b/linked-list-cycle/index.md @@ -2,6 +2,7 @@ layout: solution title: Linked List Cycle date: 2014-07-27 18:20:47 +0800 +leetcode_id: 141 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-common-prefix/index.md b/longest-common-prefix/index.md index 59663a2..d4313f0 100644 --- a/longest-common-prefix/index.md +++ b/longest-common-prefix/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Common Prefix date: 2014-08-01 17:49:20 +0800 +leetcode_id: 14 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-consecutive-sequence/index.md b/longest-consecutive-sequence/index.md index 6c3a126..212eeab 100644 --- a/longest-consecutive-sequence/index.md +++ b/longest-consecutive-sequence/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Consecutive Sequence date: 2014-08-07 20:07:11 +0800 +leetcode_id: 128 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-palindromic-substring/index.md b/longest-palindromic-substring/index.md index 2e9b3f7..3a97fa6 100644 --- a/longest-palindromic-substring/index.md +++ b/longest-palindromic-substring/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Palindromic Substring date: 2014-08-18 17:56:19 +0800 +leetcode_id: 5 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-substring-with-at-most-two-distinct-characters/index.md b/longest-substring-with-at-most-two-distinct-characters/index.md index 0a81a0d..e87fff0 100644 --- a/longest-substring-with-at-most-two-distinct-characters/index.md +++ b/longest-substring-with-at-most-two-distinct-characters/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Substring with At Most Two Distinct Characters date: 2014-12-15 18:13:21 +0800 +leetcode_id: 159 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-substring-without-repeating-characters/index.md b/longest-substring-without-repeating-characters/index.md index 137e728..90804a8 100644 --- a/longest-substring-without-repeating-characters/index.md +++ b/longest-substring-without-repeating-characters/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Substring Without Repeating Characters date: 2014-08-12 00:32:47 +0800 +leetcode_id: 3 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/longest-valid-parentheses/index.md b/longest-valid-parentheses/index.md index 33b521c..0b037f3 100644 --- a/longest-valid-parentheses/index.md +++ b/longest-valid-parentheses/index.md @@ -2,6 +2,7 @@ layout: solution title: Longest Valid Parentheses date: 2014-08-12 17:28:23 +0800 +leetcode_id: 32 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/lru-cache/index.md b/lru-cache/index.md index 80251db..07c531f 100644 --- a/lru-cache/index.md +++ b/lru-cache/index.md @@ -2,6 +2,7 @@ layout: solution title: LRU Cache date: 2014-07-28 01:06:09 +0800 +leetcode_id: 146 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/majority-element/index.md b/majority-element/index.md index a8e735d..1f0d4e9 100644 --- a/majority-element/index.md +++ b/majority-element/index.md @@ -2,6 +2,7 @@ layout: solution title: Majority Element date: 2014-12-22 15:14:45 +0800 +leetcode_id: 169 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/max-points-on-a-line/index.md b/max-points-on-a-line/index.md index b61deae..fa12cdb 100644 --- a/max-points-on-a-line/index.md +++ b/max-points-on-a-line/index.md @@ -2,6 +2,7 @@ layout: solution title: Max Points on a Line date: 2014-07-25 12:40:38 +0800 +leetcode_id: 149 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximal-rectangle/index.md b/maximal-rectangle/index.md index 5075cd7..8c4b561 100644 --- a/maximal-rectangle/index.md +++ b/maximal-rectangle/index.md @@ -2,6 +2,7 @@ layout: solution title: Maximal Rectangle date: 2014-08-03 09:01:30 +0800 +leetcode_id: 85 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximum-depth-of-binary-tree/index.md b/maximum-depth-of-binary-tree/index.md index c5361f6..ac93068 100644 --- a/maximum-depth-of-binary-tree/index.md +++ b/maximum-depth-of-binary-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Maximum Depth of Binary Tree date: 2014-08-01 01:25:55 +0800 +leetcode_id: 104 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximum-gap/index.md b/maximum-gap/index.md index 9c1467b..b1cc59b 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -2,6 +2,7 @@ layout: solution title: Maximum Gap date: 2014-12-16 01:13:52 +0800 +leetcode_id: 164 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximum-product-subarray/index.md b/maximum-product-subarray/index.md index 8a647ed..b62014f 100644 --- a/maximum-product-subarray/index.md +++ b/maximum-product-subarray/index.md @@ -2,6 +2,7 @@ layout: solution title: Maximum Product Subarray date: 2014-09-24 23:57:39 +0800 +leetcode_id: 152 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/maximum-subarray/index.md b/maximum-subarray/index.md index c7f4b85..3546216 100644 --- a/maximum-subarray/index.md +++ b/maximum-subarray/index.md @@ -2,6 +2,7 @@ layout: solution title: Maximum Subarray date: 2014-08-07 14:22:53 +0800 +leetcode_id: 53 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/median-of-two-sorted-arrays/index.md b/median-of-two-sorted-arrays/index.md index 0f81bc1..1070f61 100644 --- a/median-of-two-sorted-arrays/index.md +++ b/median-of-two-sorted-arrays/index.md @@ -2,6 +2,7 @@ layout: solution title: Median of Two Sorted Arrays date: 2014-08-11 19:38:54 +0800 +leetcode_id: 4 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/merge-intervals/index.md b/merge-intervals/index.md index ddd0721..bef0a8c 100644 --- a/merge-intervals/index.md +++ b/merge-intervals/index.md @@ -2,6 +2,7 @@ layout: solution title: Merge Intervals date: 2014-07-29 16:56:39 +0800 +leetcode_id: 56 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/merge-k-sorted-lists/index.md b/merge-k-sorted-lists/index.md index f6c72ba..2c5aa24 100644 --- a/merge-k-sorted-lists/index.md +++ b/merge-k-sorted-lists/index.md @@ -2,6 +2,7 @@ layout: solution title: Merge k Sorted Lists date: 2014-07-30 19:13:09 +0800 +leetcode_id: 23 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/merge-sorted-array/index.md b/merge-sorted-array/index.md index cebb2e2..92af976 100644 --- a/merge-sorted-array/index.md +++ b/merge-sorted-array/index.md @@ -2,6 +2,7 @@ layout: solution title: Merge Sorted Array date: 2014-07-24 18:38:41 +0800 +leetcode_id: 88 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/merge-two-sorted-lists/index.md b/merge-two-sorted-lists/index.md index 4a632fb..4630687 100644 --- a/merge-two-sorted-lists/index.md +++ b/merge-two-sorted-lists/index.md @@ -2,6 +2,7 @@ layout: solution title: Merge Two Sorted Lists date: 2014-07-30 18:58:49 +0800 +leetcode_id: 21 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/min-stack/index.md b/min-stack/index.md index ea546f4..4e7143f 100644 --- a/min-stack/index.md +++ b/min-stack/index.md @@ -2,6 +2,7 @@ layout: solution title: Min Stack date: 2014-11-18 00:59:34 +0800 +leetcode_id: 155 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/minimum-depth-of-binary-tree/index.md b/minimum-depth-of-binary-tree/index.md index ed28852..3a1689b 100644 --- a/minimum-depth-of-binary-tree/index.md +++ b/minimum-depth-of-binary-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Minimum Depth of Binary Tree date: 2014-08-01 01:24:15 +0800 +leetcode_id: 111 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/minimum-path-sum/index.md b/minimum-path-sum/index.md index 7523684..b51af34 100644 --- a/minimum-path-sum/index.md +++ b/minimum-path-sum/index.md @@ -2,6 +2,7 @@ layout: solution title: Minimum Path Sum date: 2014-08-06 00:58:46 +0800 +leetcode_id: 64 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/minimum-window-substring/index.md b/minimum-window-substring/index.md index bcf6049..9ede576 100644 --- a/minimum-window-substring/index.md +++ b/minimum-window-substring/index.md @@ -2,6 +2,7 @@ layout: solution title: Minimum Window Substring date: 2014-08-25 00:31:17 +0800 +leetcode_id: 76 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/missing-ranges/index.md b/missing-ranges/index.md index 56802a1..6cc5240 100644 --- a/missing-ranges/index.md +++ b/missing-ranges/index.md @@ -2,6 +2,7 @@ layout: solution title: Missing Ranges date: 2014-12-16 00:23:40 +0800 +leetcode_id: 163 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/multiply-strings/index.md b/multiply-strings/index.md index 684a17a..e25a785 100644 --- a/multiply-strings/index.md +++ b/multiply-strings/index.md @@ -2,6 +2,7 @@ layout: solution title: Multiply Strings date: 2014-08-02 20:38:32 +0800 +leetcode_id: 43 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/n-queens-ii/index.md b/n-queens-ii/index.md index 67f972c..d79ab36 100644 --- a/n-queens-ii/index.md +++ b/n-queens-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: N-Queens II date: 2014-07-31 18:58:00 +0800 +leetcode_id: 52 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/n-queens/index.md b/n-queens/index.md index b273dac..31f72f7 100644 --- a/n-queens/index.md +++ b/n-queens/index.md @@ -2,6 +2,7 @@ layout: solution title: N-Queens date: 2014-08-01 01:00:44 +0800 +leetcode_id: 51 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/next-permutation/index.md b/next-permutation/index.md index 44adaab..5eac976 100644 --- a/next-permutation/index.md +++ b/next-permutation/index.md @@ -2,6 +2,7 @@ layout: solution title: Next Permutation date: 2014-08-31 00:42:19 +0800 +leetcode_id: 31 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/one-edit-distance/index.md b/one-edit-distance/index.md index 66b01f0..21422d7 100644 --- a/one-edit-distance/index.md +++ b/one-edit-distance/index.md @@ -2,6 +2,7 @@ layout: solution title: One Edit Distance date: 2014-12-15 18:35:04 +0800 +leetcode_id: 161 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/palindrome-number/index.md b/palindrome-number/index.md index 4507cfd..c54cc43 100644 --- a/palindrome-number/index.md +++ b/palindrome-number/index.md @@ -2,6 +2,7 @@ layout: solution title: Palindrome Number date: 2014-07-31 22:24:16 +0800 +leetcode_id: 9 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/palindrome-partitioning-ii/index.md b/palindrome-partitioning-ii/index.md index ccce0ec..9106cd7 100644 --- a/palindrome-partitioning-ii/index.md +++ b/palindrome-partitioning-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Palindrome Partitioning II date: 2014-08-22 20:14:10 +0800 +leetcode_id: 132 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/palindrome-partitioning/index.md b/palindrome-partitioning/index.md index cf94244..5009fb9 100644 --- a/palindrome-partitioning/index.md +++ b/palindrome-partitioning/index.md @@ -2,6 +2,7 @@ layout: solution title: Palindrome Partitioning date: 2014-08-18 23:49:32 +0800 +leetcode_id: 131 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/partition-list/index.md b/partition-list/index.md index a60df6d..3211dfe 100644 --- a/partition-list/index.md +++ b/partition-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Partition List date: 2014-07-31 15:09:14 +0800 +leetcode_id: 86 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/pascals-triangle-ii/index.md b/pascals-triangle-ii/index.md index 92ed36a..1144559 100644 --- a/pascals-triangle-ii/index.md +++ b/pascals-triangle-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Pascal's Triangle II date: 2014-07-30 11:39:03 +0800 +leetcode_id: 119 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/pascals-triangle/index.md b/pascals-triangle/index.md index 3fb655a..a7e3879 100644 --- a/pascals-triangle/index.md +++ b/pascals-triangle/index.md @@ -2,6 +2,7 @@ layout: solution title: Pascal's Triangle date: 2014-07-30 00:12:08 +0800 +leetcode_id: 118 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/path-sum-ii/index.md b/path-sum-ii/index.md index 83abdbb..ce7a453 100644 --- a/path-sum-ii/index.md +++ b/path-sum-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Path Sum II date: 2014-08-06 18:23:30 +0800 +leetcode_id: 113 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/path-sum/index.md b/path-sum/index.md index 4d309bb..41a95a0 100644 --- a/path-sum/index.md +++ b/path-sum/index.md @@ -2,6 +2,7 @@ layout: solution title: Path Sum date: 2014-08-02 01:01:57 +0800 +leetcode_id: 112 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/permutation-sequence/index.md b/permutation-sequence/index.md index 5d6bf9c..2e8756c 100644 --- a/permutation-sequence/index.md +++ b/permutation-sequence/index.md @@ -2,6 +2,7 @@ layout: solution title: Permutation Sequence date: 2014-08-29 20:57:36 +0800 +leetcode_id: 60 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/permutations-ii/index.md b/permutations-ii/index.md index 0ca9fa0..1aa0254 100644 --- a/permutations-ii/index.md +++ b/permutations-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Permutations II date: 2014-08-31 00:52:32 +0800 +leetcode_id: 47 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/permutations/index.md b/permutations/index.md index a9dc337..0f3262d 100644 --- a/permutations/index.md +++ b/permutations/index.md @@ -2,6 +2,7 @@ layout: solution title: Permutations date: 2014-08-17 23:07:06 +0800 +leetcode_id: 46 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/plus-one/index.md b/plus-one/index.md index 2e9cb94..f071ac7 100644 --- a/plus-one/index.md +++ b/plus-one/index.md @@ -2,6 +2,7 @@ layout: solution title: Plus One date: 2014-08-02 19:53:52 +0800 +leetcode_id: 66 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/populating-next-right-pointers-in-each-node-ii/index.md b/populating-next-right-pointers-in-each-node-ii/index.md index 2d0e7fb..fa6f520 100644 --- a/populating-next-right-pointers-in-each-node-ii/index.md +++ b/populating-next-right-pointers-in-each-node-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Populating Next Right Pointers in Each Node II date: 2014-08-20 17:35:02 +0800 +leetcode_id: 117 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/populating-next-right-pointers-in-each-node/index.md b/populating-next-right-pointers-in-each-node/index.md index 5cef466..9060bbd 100644 --- a/populating-next-right-pointers-in-each-node/index.md +++ b/populating-next-right-pointers-in-each-node/index.md @@ -2,6 +2,7 @@ layout: solution title: Populating Next Right Pointers in Each Node date: 2014-08-20 16:49:17 +0800 +leetcode_id: 116 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/powx-n/index.md b/powx-n/index.md index e0cfb86..05b1ab7 100644 --- a/powx-n/index.md +++ b/powx-n/index.md @@ -2,6 +2,7 @@ layout: solution title: Pow(x, n) date: 2014-07-24 18:26:54 +0800 +leetcode_id: 50 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/read-n-characters-given-read4-ii-call-multiple-times/index.md b/read-n-characters-given-read4-ii-call-multiple-times/index.md index 183cf7e..e4c494b 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/index.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/index.md @@ -2,6 +2,7 @@ layout: solution title: Read N Characters Given Read4 II - Call multiple times date: 2014-12-15 17:32:05 +0800 +leetcode_id: 158 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/read-n-characters-given-read4/index.md b/read-n-characters-given-read4/index.md index 0ad520c..7192f97 100644 --- a/read-n-characters-given-read4/index.md +++ b/read-n-characters-given-read4/index.md @@ -2,6 +2,7 @@ layout: solution title: Read N Characters Given Read4 date: 2014-12-15 17:18:30 +0800 +leetcode_id: 157 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/recover-binary-search-tree/index.md b/recover-binary-search-tree/index.md index fd74625..b368c31 100644 --- a/recover-binary-search-tree/index.md +++ b/recover-binary-search-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Recover Binary Search Tree date: 2014-08-01 18:35:38 +0800 +leetcode_id: 99 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/regular-expression-matching/index.md b/regular-expression-matching/index.md index 0dc5720..cd4f16a 100644 --- a/regular-expression-matching/index.md +++ b/regular-expression-matching/index.md @@ -2,6 +2,7 @@ layout: solution title: Regular Expression Matching date: 2014-08-02 02:43:26 +0800 +leetcode_id: 10 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-duplicates-from-sorted-array-ii/index.md b/remove-duplicates-from-sorted-array-ii/index.md index 16bbc78..a912e8e 100644 --- a/remove-duplicates-from-sorted-array-ii/index.md +++ b/remove-duplicates-from-sorted-array-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Duplicates from Sorted Array II date: 2014-08-04 14:24:32 +0800 +leetcode_id: 80 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-duplicates-from-sorted-array/index.md b/remove-duplicates-from-sorted-array/index.md index bf6e485..825969c 100644 --- a/remove-duplicates-from-sorted-array/index.md +++ b/remove-duplicates-from-sorted-array/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Duplicates from Sorted Array date: 2014-08-04 14:06:11 +0800 +leetcode_id: 26 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-duplicates-from-sorted-list-ii/index.md b/remove-duplicates-from-sorted-list-ii/index.md index 847d3ef..8eca73d 100644 --- a/remove-duplicates-from-sorted-list-ii/index.md +++ b/remove-duplicates-from-sorted-list-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Duplicates from Sorted List II date: 2014-08-04 14:37:56 +0800 +leetcode_id: 82 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-duplicates-from-sorted-list/index.md b/remove-duplicates-from-sorted-list/index.md index 5aede65..faf9f36 100644 --- a/remove-duplicates-from-sorted-list/index.md +++ b/remove-duplicates-from-sorted-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Duplicates from Sorted List date: 2014-08-04 14:37:45 +0800 +leetcode_id: 83 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-element/index.md b/remove-element/index.md index e4afc78..dd2c3de 100644 --- a/remove-element/index.md +++ b/remove-element/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Element date: 2014-07-31 15:57:51 +0800 +leetcode_id: 27 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/remove-nth-node-from-end-of-list/index.md b/remove-nth-node-from-end-of-list/index.md index d75e5ed..41cdb30 100644 --- a/remove-nth-node-from-end-of-list/index.md +++ b/remove-nth-node-from-end-of-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Remove Nth Node From End of List date: 2014-08-04 14:44:23 +0800 +leetcode_id: 19 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/reorder-list/index.md b/reorder-list/index.md index 35e574d..2ee4590 100644 --- a/reorder-list/index.md +++ b/reorder-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Reorder List date: 2014-07-29 15:26:44 +0800 +leetcode_id: 143 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/restore-ip-addresses/index.md b/restore-ip-addresses/index.md index 31c7f2e..d8b761d 100644 --- a/restore-ip-addresses/index.md +++ b/restore-ip-addresses/index.md @@ -2,6 +2,7 @@ layout: solution title: Restore IP Addresses date: 2014-08-01 18:53:49 +0800 +leetcode_id: 93 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/reverse-integer/index.md b/reverse-integer/index.md index 50304ce..9ec66df 100644 --- a/reverse-integer/index.md +++ b/reverse-integer/index.md @@ -2,6 +2,7 @@ layout: solution title: Reverse Integer date: 2014-08-04 13:40:44 +0800 +leetcode_id: 7 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/reverse-linked-list-ii/index.md b/reverse-linked-list-ii/index.md index 807dabe..d6f4bd4 100644 --- a/reverse-linked-list-ii/index.md +++ b/reverse-linked-list-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Reverse Linked List II date: 2014-08-04 15:17:26 +0800 +leetcode_id: 92 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/reverse-nodes-in-k-group/index.md b/reverse-nodes-in-k-group/index.md index 9ed0fed..9a520e8 100644 --- a/reverse-nodes-in-k-group/index.md +++ b/reverse-nodes-in-k-group/index.md @@ -2,6 +2,7 @@ layout: solution title: Reverse Nodes in k-Group date: 2014-08-04 15:23:50 +0800 +leetcode_id: 25 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/reverse-words-in-a-string/index.md b/reverse-words-in-a-string/index.md index e94b683..fd90697 100644 --- a/reverse-words-in-a-string/index.md +++ b/reverse-words-in-a-string/index.md @@ -2,6 +2,7 @@ layout: solution title: Reverse Words in a String date: 2014-08-01 14:19:34 +0800 +leetcode_id: 151 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/roman-to-integer/index.md b/roman-to-integer/index.md index 4513c36..f8bbe11 100644 --- a/roman-to-integer/index.md +++ b/roman-to-integer/index.md @@ -2,6 +2,7 @@ layout: solution title: Roman to Integer date: 2014-07-31 13:56:29 +0800 +leetcode_id: 13 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/rotate-image/index.md b/rotate-image/index.md index 6e35f7e..a9398d9 100644 --- a/rotate-image/index.md +++ b/rotate-image/index.md @@ -2,6 +2,7 @@ layout: solution title: Rotate Image date: 2014-08-28 16:12:56 +0800 +leetcode_id: 48 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/rotate-list/index.md b/rotate-list/index.md index 484276e..18d5da1 100644 --- a/rotate-list/index.md +++ b/rotate-list/index.md @@ -2,6 +2,7 @@ layout: solution title: Rotate List date: 2014-08-04 15:10:53 +0800 +leetcode_id: 61 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/same-tree/index.md b/same-tree/index.md index dcfe53a..4b9b2f7 100644 --- a/same-tree/index.md +++ b/same-tree/index.md @@ -2,6 +2,7 @@ layout: solution title: Same Tree date: 2014-07-23 18:53:33 +0800 +leetcode_id: 100 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/scramble-string/index.md b/scramble-string/index.md index bf52c9d..0c656fd 100644 --- a/scramble-string/index.md +++ b/scramble-string/index.md @@ -2,6 +2,7 @@ layout: solution title: Scramble String date: 2014-07-24 19:07:16 +0800 +leetcode_id: 87 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/search-a-2d-matrix/index.md b/search-a-2d-matrix/index.md index 83d9184..2822a2b 100644 --- a/search-a-2d-matrix/index.md +++ b/search-a-2d-matrix/index.md @@ -2,6 +2,7 @@ layout: solution title: Search a 2D Matrix date: 2014-08-04 13:33:58 +0800 +leetcode_id: 74 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/search-for-a-range/index.md b/search-for-a-range/index.md index fea733f..4c5c7c5 100644 --- a/search-for-a-range/index.md +++ b/search-for-a-range/index.md @@ -2,6 +2,7 @@ layout: solution title: Search for a Range date: 2014-07-27 00:31:27 +0800 +leetcode_id: 34 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/search-in-rotated-sorted-array-ii/index.md b/search-in-rotated-sorted-array-ii/index.md index bf5c758..1e616e4 100644 --- a/search-in-rotated-sorted-array-ii/index.md +++ b/search-in-rotated-sorted-array-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Search in Rotated Sorted Array II date: 2014-08-02 21:27:14 +0800 +leetcode_id: 81 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/search-in-rotated-sorted-array/index.md b/search-in-rotated-sorted-array/index.md index c08862c..5a02627 100644 --- a/search-in-rotated-sorted-array/index.md +++ b/search-in-rotated-sorted-array/index.md @@ -2,6 +2,7 @@ layout: solution title: Search in Rotated Sorted Array date: 2014-07-29 19:03:11 +0800 +leetcode_id: 33 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/search-insert-position/index.md b/search-insert-position/index.md index e455717..c24c1aa 100644 --- a/search-insert-position/index.md +++ b/search-insert-position/index.md @@ -2,6 +2,7 @@ layout: solution title: Search Insert Position date: 2014-07-31 00:22:36 +0800 +leetcode_id: 35 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/set-matrix-zeroes/index.md b/set-matrix-zeroes/index.md index d5acba5..3ef92a1 100644 --- a/set-matrix-zeroes/index.md +++ b/set-matrix-zeroes/index.md @@ -2,6 +2,7 @@ layout: solution title: Set Matrix Zeroes date: 2014-08-01 16:21:17 +0800 +leetcode_id: 73 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/simplify-path/index.md b/simplify-path/index.md index c09477f..d4996dc 100644 --- a/simplify-path/index.md +++ b/simplify-path/index.md @@ -2,6 +2,7 @@ layout: solution title: Simplify Path date: 2014-08-02 23:57:16 +0800 +leetcode_id: 71 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/single-number-ii/index.md b/single-number-ii/index.md index 3eae5a4..d2735c9 100644 --- a/single-number-ii/index.md +++ b/single-number-ii/index.md @@ -2,6 +2,7 @@ layout: solution title: Single Number II date: 2014-08-04 15:03:21 +0800 +leetcode_id: 137 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/single-number/index.md b/single-number/index.md index 60723cc..bc67c6e 100644 --- a/single-number/index.md +++ b/single-number/index.md @@ -2,6 +2,7 @@ layout: solution title: Single Number date: 2014-07-26 23:49:23 +0800 +leetcode_id: 136 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} {% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} diff --git a/skeleton.sh b/skeleton.sh index f7a02a6..c249e26 100755 --- a/skeleton.sh +++ b/skeleton.sh @@ -18,6 +18,7 @@ cat > $leetcode_name/index.md < Date: Mon, 29 Dec 2014 00:26:24 +0800 Subject: [PATCH 030/195] change all file to unix format --- 3sum-closest/Solution.java | 70 +-- 3sum/Solution.java | 76 +-- 4sum/Solution.java | 166 +++---- _includes/_root/3sum-closest/Solution.java | 70 +-- _includes/_root/3sum/Solution.java | 76 +-- _includes/_root/4sum/Solution.java | 166 +++---- _includes/_root/add-binary/Solution.java | 92 ++-- _includes/_root/add-two-numbers/Solution.java | 98 ++-- _includes/_root/anagrams/Solution.java | 64 +-- .../_root/balanced-binary-tree/Solution.java | 58 +-- .../Solution.java | 46 +- .../Solution.java | 64 +-- .../Solution.java | 34 +- .../Solution.java | 136 +++--- .../Solution.java | 92 ++-- .../Solution.java | 96 ++-- .../Solution.java | 70 +-- .../Solution.java | 138 +++--- .../Solution.java | 136 +++--- .../Solution.java | 116 ++--- _includes/_root/candy/Solution.java | 50 +- _includes/_root/climbing-stairs/Solution.java | 36 +- _includes/_root/clone-graph/Solution.java | 106 ++-- .../_root/combination-sum-ii/Solution.java | 126 ++--- _includes/_root/combination-sum/Solution.java | 112 ++--- _includes/_root/combinations/Solution.java | 78 +-- .../Solution.java | 78 +-- .../Solution.java | 86 ++-- .../container-with-most-water/Solution.java | 62 +-- .../Solution.java | 62 +-- .../Solution.java | 104 ++-- .../Solution.java | 74 +-- _includes/_root/count-and-say/Solution.java | 88 ++-- _includes/_root/decode-ways/Solution.java | 76 +-- .../_root/distinct-subsequences/Solution.java | 98 ++-- .../_root/divide-two-integers/Solution.java | 86 ++-- _includes/_root/edit-distance/Solution.java | 76 +-- .../Solution.java | 70 +-- .../Solution.java | 60 +-- .../Solution.java | 50 +- _includes/_root/find-peak-element/README.md | 22 +- .../first-missing-positive/Solution.java | 78 +-- .../Solution.java | 76 +-- _includes/_root/gas-station/Solution.java | 52 +- .../_root/generate-parentheses/Solution.java | 56 +-- _includes/_root/gray-code/Solution.java | 28 +- .../_root/implement-strstr/Solution.java | 88 ++-- _includes/_root/insert-interval/Solution.java | 90 ++-- .../_root/insertion-sort-list/Solution.java | 116 ++--- .../_root/integer-to-roman/Solution.java | 120 ++--- .../_root/interleaving-string/Solution.java | 88 ++-- .../README.md | 44 +- _includes/_root/jump-game-ii/Solution.java | 40 +- _includes/_root/jump-game/Solution.java | 50 +- .../Solution.java | 102 ++-- .../_root/length-of-last-word/Solution.java | 40 +- .../Solution.java | 88 ++-- .../_root/linked-list-cycle-ii/Solution.java | 138 +++--- .../_root/linked-list-cycle/Solution.java | 72 +-- .../_root/longest-common-prefix/Solution.java | 62 +-- .../Solution.java | 74 +-- .../Solution.java | 80 +-- .../README.md | 72 +-- .../Solution.java | 54 +- .../longest-valid-parentheses/Solution.java | 66 +-- _includes/_root/lru-cache/Solution.java | 298 +++++------ .../_root/max-points-on-a-line/Solution.java | 154 +++--- .../_root/maximal-rectangle/Solution.java | 230 ++++----- .../Solution.java | 34 +- _includes/_root/maximum-gap/README.md | 64 +-- .../_root/maximum-subarray/Solution.java | 40 +- .../median-of-two-sorted-arrays/Solution.java | 158 +++--- _includes/_root/merge-intervals/Solution.java | 78 +-- .../_root/merge-k-sorted-lists/Solution.java | 94 ++-- .../_root/merge-sorted-array/Solution.java | 64 +-- .../merge-two-sorted-lists/Solution.java | 74 +-- .../Solution.java | 44 +- .../_root/minimum-path-sum/Solution.java | 54 +- .../minimum-window-substring/Solution.java | 126 ++--- _includes/_root/missing-ranges/README.md | 126 ++--- .../_root/multiply-strings/Solution.java | 80 +-- _includes/_root/n-queens-ii/Solution.java | 114 ++--- _includes/_root/n-queens/Solution.java | 134 ++--- .../_root/next-permutation/Solution.java | 76 +-- _includes/_root/one-edit-distance/README.md | 52 +- .../_root/palindrome-number/Solution.java | 50 +- .../palindrome-partitioning-ii/Solution.java | 98 ++-- .../palindrome-partitioning/Solution.java | 88 ++-- _includes/_root/partition-list/Solution.java | 86 ++-- .../_root/pascals-triangle-ii/Solution.java | 30 +- .../_root/pascals-triangle/Solution.java | 56 +-- _includes/_root/path-sum-ii/Solution.java | 88 ++-- _includes/_root/path-sum/Solution.java | 52 +- .../_root/permutation-sequence/Solution.java | 78 +-- _includes/_root/permutations-ii/Solution.java | 122 ++--- _includes/_root/permutations/Solution.java | 70 +-- _includes/_root/plus-one/Solution.java | 32 +- .../Solution.java | 92 ++-- .../Solution.java | 50 +- _includes/_root/powx-n/Solution.java | 34 +- .../README.md | 46 +- .../read-n-characters-given-read4/README.md | 28 +- .../recover-binary-search-tree/Solution.java | 104 ++-- .../regular-expression-matching/Solution.java | 462 +++++++++--------- .../Solution.java | 48 +- .../Solution.java | 36 +- .../Solution.java | 72 +-- .../Solution.java | 70 +-- _includes/_root/remove-element/Solution.java | 30 +- .../Solution.java | 70 +-- _includes/_root/reorder-list/Solution.java | 148 +++--- .../_root/restore-ip-addresses/Solution.java | 92 ++-- _includes/_root/reverse-integer/Solution.java | 44 +- .../reverse-linked-list-ii/Solution.java | 126 ++--- .../reverse-nodes-in-k-group/Solution.java | 112 ++--- .../reverse-words-in-a-string/Solution.java | 68 +-- .../_root/roman-to-integer/Solution.java | 108 ++-- _includes/_root/rotate-image/Solution.java | 74 +-- _includes/_root/rotate-list/Solution.java | 80 +-- _includes/_root/same-tree/Solution.java | 40 +- _includes/_root/scramble-string/Solution.java | 344 ++++++------- .../_root/search-a-2d-matrix/Solution.java | 58 +-- .../_root/search-for-a-range/Solution.java | 56 +-- .../Solution.java | 118 ++--- .../Solution.java | 84 ++-- .../search-insert-position/Solution.java | 16 +- .../_root/set-matrix-zeroes/Solution.java | 128 ++--- _includes/_root/simplify-path/Solution.java | 88 ++-- .../_root/single-number-ii/Solution.java | 62 +-- _includes/_root/single-number/Solution.java | 24 +- _includes/_root/sort-colors/Solution.java | 70 +-- _includes/_root/sort-list/Solution.java | 118 ++--- .../_root/spiral-matrix-ii/Solution.java | 84 ++-- _includes/_root/spiral-matrix/Solution.java | 82 ++-- _includes/_root/sqrtx/Solution.java | 82 ++-- .../string-to-integer-atoi/Solution.java | 126 ++--- _includes/_root/subsets-ii/Solution.java | 98 ++-- _includes/_root/subsets/Solution.java | 68 +-- .../Solution.java | 120 ++--- _includes/_root/sudoku-solver/Solution.java | 234 ++++----- .../sum-root-to-leaf-numbers/Solution.java | 54 +- .../_root/surrounded-regions/Solution.java | 200 ++++---- .../_root/swap-nodes-in-pairs/Solution.java | 54 +- _includes/_root/symmetric-tree/Solution.java | 150 +++--- .../_root/text-justification/Solution.java | 128 ++--- .../_root/trapping-rain-water/Solution.java | 144 +++--- _includes/_root/triangle/Solution.java | 54 +- _includes/_root/two-sum/Solution.java | 42 +- .../Solution.java | 84 ++-- .../unique-binary-search-trees/Solution.java | 28 +- _includes/_root/unique-paths-ii/Solution.java | 78 +-- _includes/_root/unique-paths/Solution.java | 50 +- _includes/_root/valid-number/Solution.java | 86 ++-- .../_root/valid-palindrome/Solution.java | 58 +-- .../_root/valid-parentheses/Solution.java | 58 +-- _includes/_root/valid-sudoku/Solution.java | 108 ++-- .../validate-binary-search-tree/Solution.java | 74 +-- .../_root/wildcard-matching/Solution.java | 114 ++--- _includes/_root/word-break-ii/Solution.java | 134 ++--- _includes/_root/word-break/Solution.java | 44 +- _includes/_root/word-ladder-ii/Solution.java | 272 +++++------ _includes/_root/word-ladder/Solution.java | 118 ++--- _includes/_root/word-search/Solution.java | 168 +++---- .../_root/zigzag-conversion/Solution.java | 110 ++--- add-binary/Solution.java | 92 ++-- add-two-numbers/Solution.java | 98 ++-- anagrams/Solution.java | 64 +-- balanced-binary-tree/Solution.java | 58 +-- .../Solution.java | 46 +- .../Solution.java | 64 +-- best-time-to-buy-and-sell-stock/Solution.java | 34 +- binary-tree-inorder-traversal/Solution.java | 136 +++--- .../Solution.java | 92 ++-- .../Solution.java | 96 ++-- binary-tree-maximum-path-sum/Solution.java | 70 +-- binary-tree-postorder-traversal/Solution.java | 138 +++--- binary-tree-preorder-traversal/Solution.java | 136 +++--- .../Solution.java | 116 ++--- candy/Solution.java | 50 +- climbing-stairs/Solution.java | 36 +- clone-graph/Solution.java | 106 ++-- combination-sum-ii/Solution.java | 126 ++--- combination-sum/Solution.java | 112 ++--- combinations/Solution.java | 78 +-- .../Solution.java | 78 +-- .../Solution.java | 86 ++-- container-with-most-water/Solution.java | 62 +-- .../Solution.java | 62 +-- .../Solution.java | 104 ++-- copy-list-with-random-pointer/Solution.java | 74 +-- count-and-say/Solution.java | 88 ++-- decode-ways/Solution.java | 76 +-- distinct-subsequences/Solution.java | 98 ++-- divide-two-integers/Solution.java | 86 ++-- edit-distance/Solution.java | 76 +-- .../Solution.java | 70 +-- .../Solution.java | 60 +-- .../Solution.java | 50 +- find-peak-element/README.md | 22 +- first-missing-positive/Solution.java | 78 +-- .../Solution.java | 76 +-- gas-station/Solution.java | 52 +- generate-parentheses/Solution.java | 56 +-- gray-code/Solution.java | 28 +- implement-strstr/Solution.java | 88 ++-- insert-interval/Solution.java | 90 ++-- insertion-sort-list/Solution.java | 116 ++--- integer-to-roman/Solution.java | 120 ++--- interleaving-string/Solution.java | 88 ++-- intersection-of-two-linked-lists/README.md | 44 +- jump-game-ii/Solution.java | 40 +- jump-game/Solution.java | 50 +- largest-rectangle-in-histogram/Solution.java | 102 ++-- length-of-last-word/Solution.java | 40 +- .../Solution.java | 88 ++-- linked-list-cycle-ii/Solution.java | 138 +++--- linked-list-cycle/Solution.java | 72 +-- longest-common-prefix/Solution.java | 62 +-- longest-consecutive-sequence/Solution.java | 74 +-- longest-palindromic-substring/Solution.java | 80 +-- .../README.md | 72 +-- .../Solution.java | 54 +- longest-valid-parentheses/Solution.java | 66 +-- lru-cache/Solution.java | 298 +++++------ max-points-on-a-line/Solution.java | 154 +++--- maximal-rectangle/Solution.java | 230 ++++----- maximum-depth-of-binary-tree/Solution.java | 34 +- maximum-gap/README.md | 64 +-- maximum-subarray/Solution.java | 40 +- median-of-two-sorted-arrays/Solution.java | 158 +++--- merge-intervals/Solution.java | 78 +-- merge-k-sorted-lists/Solution.java | 94 ++-- merge-sorted-array/Solution.java | 64 +-- merge-two-sorted-lists/Solution.java | 74 +-- minimum-depth-of-binary-tree/Solution.java | 44 +- minimum-path-sum/Solution.java | 54 +- minimum-window-substring/Solution.java | 126 ++--- missing-ranges/README.md | 126 ++--- multiply-strings/Solution.java | 80 +-- n-queens-ii/Solution.java | 114 ++--- n-queens/Solution.java | 134 ++--- next-permutation/Solution.java | 76 +-- one-edit-distance/README.md | 52 +- palindrome-number/Solution.java | 50 +- palindrome-partitioning-ii/Solution.java | 98 ++-- palindrome-partitioning/Solution.java | 88 ++-- partition-list/Solution.java | 86 ++-- pascals-triangle-ii/Solution.java | 30 +- pascals-triangle/Solution.java | 56 +-- path-sum-ii/Solution.java | 88 ++-- path-sum/Solution.java | 52 +- permutation-sequence/Solution.java | 78 +-- permutations-ii/Solution.java | 122 ++--- permutations/Solution.java | 70 +-- plus-one/Solution.java | 32 +- .../Solution.java | 92 ++-- .../Solution.java | 50 +- powx-n/Solution.java | 34 +- .../README.md | 46 +- read-n-characters-given-read4/README.md | 28 +- recover-binary-search-tree/Solution.java | 104 ++-- regular-expression-matching/Solution.java | 462 +++++++++--------- .../Solution.java | 48 +- .../Solution.java | 36 +- .../Solution.java | 72 +-- .../Solution.java | 70 +-- remove-element/Solution.java | 30 +- .../Solution.java | 70 +-- reorder-list/Solution.java | 148 +++--- restore-ip-addresses/Solution.java | 92 ++-- reverse-integer/Solution.java | 44 +- reverse-linked-list-ii/Solution.java | 126 ++--- reverse-nodes-in-k-group/Solution.java | 112 ++--- reverse-words-in-a-string/Solution.java | 68 +-- roman-to-integer/Solution.java | 108 ++-- rotate-image/Solution.java | 74 +-- rotate-list/Solution.java | 80 +-- same-tree/Solution.java | 40 +- scramble-string/Solution.java | 344 ++++++------- search-a-2d-matrix/Solution.java | 58 +-- search-for-a-range/Solution.java | 56 +-- .../Solution.java | 118 ++--- search-in-rotated-sorted-array/Solution.java | 84 ++-- search-insert-position/Solution.java | 16 +- set-matrix-zeroes/Solution.java | 128 ++--- simplify-path/Solution.java | 88 ++-- single-number-ii/Solution.java | 62 +-- single-number/Solution.java | 24 +- sort-colors/Solution.java | 70 +-- sort-list/Solution.java | 118 ++--- spiral-matrix-ii/Solution.java | 84 ++-- spiral-matrix/Solution.java | 82 ++-- sqrtx/Solution.java | 82 ++-- string-to-integer-atoi/Solution.java | 126 ++--- subsets-ii/Solution.java | 98 ++-- subsets/Solution.java | 68 +-- .../Solution.java | 120 ++--- sudoku-solver/Solution.java | 234 ++++----- sum-root-to-leaf-numbers/Solution.java | 54 +- surrounded-regions/Solution.java | 200 ++++---- swap-nodes-in-pairs/Solution.java | 54 +- symmetric-tree/Solution.java | 150 +++--- text-justification/Solution.java | 128 ++--- trapping-rain-water/Solution.java | 144 +++--- triangle/Solution.java | 54 +- two-sum/Solution.java | 42 +- unique-binary-search-trees-ii/Solution.java | 84 ++-- unique-binary-search-trees/Solution.java | 28 +- unique-paths-ii/Solution.java | 78 +-- unique-paths/Solution.java | 50 +- valid-number/Solution.java | 86 ++-- valid-palindrome/Solution.java | 58 +-- valid-parentheses/Solution.java | 58 +-- valid-sudoku/Solution.java | 108 ++-- validate-binary-search-tree/Solution.java | 74 +-- wildcard-matching/Solution.java | 114 ++--- word-break-ii/Solution.java | 134 ++--- word-break/Solution.java | 44 +- word-ladder-ii/Solution.java | 272 +++++------ word-ladder/Solution.java | 118 ++--- word-search/Solution.java | 168 +++---- zigzag-conversion/Solution.java | 110 ++--- 322 files changed, 14374 insertions(+), 14374 deletions(-) diff --git a/3sum-closest/Solution.java b/3sum-closest/Solution.java index 6c5ade6..1554858 100644 --- a/3sum-closest/Solution.java +++ b/3sum-closest/Solution.java @@ -1,36 +1,36 @@ -public class Solution { - public int threeSumClosest(int[] num, int target) { - - if(num.length < 3) return 0; - - Arrays.sort(num); - - int pneg = 0 , ppos = num.length - 1; - - int closest = num[0] + num[1] + num[2]; - - while(ppos > 0){ - while(pneg < ppos){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(Math.abs(target - (num[i] + sum)) < Math.abs(target - closest) ){ - closest = num[i] + sum; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return closest; - } +public class Solution { + public int threeSumClosest(int[] num, int target) { + + if(num.length < 3) return 0; + + Arrays.sort(num); + + int pneg = 0 , ppos = num.length - 1; + + int closest = num[0] + num[1] + num[2]; + + while(ppos > 0){ + while(pneg < ppos){ + int sum = num[pneg]; + sum += num[ppos]; + + for(int i = pneg + 1; i < ppos; i++){ + if(Math.abs(target - (num[i] + sum)) < Math.abs(target - closest) ){ + closest = num[i] + sum; + } + } + + int old = num[pneg]; + while(pneg < ppos && num[pneg] == old) pneg++; + } + + pneg = 0; + + int old = num[ppos]; + while(ppos > 0 && num[ppos] == old) ppos--; + } + + + return closest; + } } \ No newline at end of file diff --git a/3sum/Solution.java b/3sum/Solution.java index e46b632..a158e28 100644 --- a/3sum/Solution.java +++ b/3sum/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public List> threeSum(int[] num) { - - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - - int pneg = 0 , ppos = num.length - 1; - - - while(ppos > 0 && num[ppos] >= 0){ - while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(num[i] + sum == 0){ - found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); - - break; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return found; - - } -} +public class Solution { + public List> threeSum(int[] num) { + + Arrays.sort(num); + + ArrayList> found = new ArrayList>(); + + int pneg = 0 , ppos = num.length - 1; + + + while(ppos > 0 && num[ppos] >= 0){ + while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ + int sum = num[pneg]; + sum += num[ppos]; + + for(int i = pneg + 1; i < ppos; i++){ + if(num[i] + sum == 0){ + found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); + + break; + } + } + + int old = num[pneg]; + while(pneg < ppos && num[pneg] == old) pneg++; + } + + pneg = 0; + + int old = num[ppos]; + while(ppos > 0 && num[ppos] == old) ppos--; + } + + + return found; + + } +} diff --git a/4sum/Solution.java b/4sum/Solution.java index 5b372d9..2992b72 100644 --- a/4sum/Solution.java +++ b/4sum/Solution.java @@ -1,83 +1,83 @@ -public class Solution { - - static class TwoSum { - int index1; - int index2; - - boolean overlap(TwoSum other){ - if(this == other) return true; - - if(index1 == other.index1) return true; - if(index2 == other.index1) return true; - - if(index1 == other.index2) return true; - if(index2 == other.index2) return true; - - return false; - } - } - - public List> fourSum(int[] num, int target) { - ArrayList> found = new ArrayList>(); - - if(num.length < 4) return found; - - HashMap> cache = new HashMap>(); - - Arrays.sort(num); - - for(int i = 0; i < num.length; i++){ - for(int j = i + 1; j < num.length; j++){ - - int s = num[i] + num[j]; - TwoSum t = new TwoSum(); - - t.index1 = i; - t.index2 = j; - - ArrayList l = cache.get(s); - if(l == null){ - l = new ArrayList(); - cache.put(s, l); - } - - l.add(t); - } - } - - HashSet block = new HashSet(); - - for(Integer a : cache.keySet()){ - Integer b = target - a; - - ArrayList lsb = cache.get(b); - if(lsb != null){ - ArrayList lsa = cache.get(a); - - for(TwoSum sa : lsa) - for(TwoSum sb : lsb){ - - if(sa.overlap(sb)) continue; - - Integer[] sol = new Integer[]{num[sa.index1], num[sa.index2], num[sb.index1], num[sb.index2]}; - Arrays.sort(sol); - - String uid = Arrays.toString(sol); - if(!block.contains(uid)){ - found.add(Arrays.asList(sol)); - - block.add(uid); - } - - - } - - cache.put(a, null); - cache.put(b, null); - } - } - - - return found; - } -} +public class Solution { + + static class TwoSum { + int index1; + int index2; + + boolean overlap(TwoSum other){ + if(this == other) return true; + + if(index1 == other.index1) return true; + if(index2 == other.index1) return true; + + if(index1 == other.index2) return true; + if(index2 == other.index2) return true; + + return false; + } + } + + public List> fourSum(int[] num, int target) { + ArrayList> found = new ArrayList>(); + + if(num.length < 4) return found; + + HashMap> cache = new HashMap>(); + + Arrays.sort(num); + + for(int i = 0; i < num.length; i++){ + for(int j = i + 1; j < num.length; j++){ + + int s = num[i] + num[j]; + TwoSum t = new TwoSum(); + + t.index1 = i; + t.index2 = j; + + ArrayList l = cache.get(s); + if(l == null){ + l = new ArrayList(); + cache.put(s, l); + } + + l.add(t); + } + } + + HashSet block = new HashSet(); + + for(Integer a : cache.keySet()){ + Integer b = target - a; + + ArrayList lsb = cache.get(b); + if(lsb != null){ + ArrayList lsa = cache.get(a); + + for(TwoSum sa : lsa) + for(TwoSum sb : lsb){ + + if(sa.overlap(sb)) continue; + + Integer[] sol = new Integer[]{num[sa.index1], num[sa.index2], num[sb.index1], num[sb.index2]}; + Arrays.sort(sol); + + String uid = Arrays.toString(sol); + if(!block.contains(uid)){ + found.add(Arrays.asList(sol)); + + block.add(uid); + } + + + } + + cache.put(a, null); + cache.put(b, null); + } + } + + + return found; + } +} diff --git a/_includes/_root/3sum-closest/Solution.java b/_includes/_root/3sum-closest/Solution.java index 6c5ade6..1554858 100644 --- a/_includes/_root/3sum-closest/Solution.java +++ b/_includes/_root/3sum-closest/Solution.java @@ -1,36 +1,36 @@ -public class Solution { - public int threeSumClosest(int[] num, int target) { - - if(num.length < 3) return 0; - - Arrays.sort(num); - - int pneg = 0 , ppos = num.length - 1; - - int closest = num[0] + num[1] + num[2]; - - while(ppos > 0){ - while(pneg < ppos){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(Math.abs(target - (num[i] + sum)) < Math.abs(target - closest) ){ - closest = num[i] + sum; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return closest; - } +public class Solution { + public int threeSumClosest(int[] num, int target) { + + if(num.length < 3) return 0; + + Arrays.sort(num); + + int pneg = 0 , ppos = num.length - 1; + + int closest = num[0] + num[1] + num[2]; + + while(ppos > 0){ + while(pneg < ppos){ + int sum = num[pneg]; + sum += num[ppos]; + + for(int i = pneg + 1; i < ppos; i++){ + if(Math.abs(target - (num[i] + sum)) < Math.abs(target - closest) ){ + closest = num[i] + sum; + } + } + + int old = num[pneg]; + while(pneg < ppos && num[pneg] == old) pneg++; + } + + pneg = 0; + + int old = num[ppos]; + while(ppos > 0 && num[ppos] == old) ppos--; + } + + + return closest; + } } \ No newline at end of file diff --git a/_includes/_root/3sum/Solution.java b/_includes/_root/3sum/Solution.java index e46b632..a158e28 100644 --- a/_includes/_root/3sum/Solution.java +++ b/_includes/_root/3sum/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public List> threeSum(int[] num) { - - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - - int pneg = 0 , ppos = num.length - 1; - - - while(ppos > 0 && num[ppos] >= 0){ - while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(num[i] + sum == 0){ - found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); - - break; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return found; - - } -} +public class Solution { + public List> threeSum(int[] num) { + + Arrays.sort(num); + + ArrayList> found = new ArrayList>(); + + int pneg = 0 , ppos = num.length - 1; + + + while(ppos > 0 && num[ppos] >= 0){ + while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ + int sum = num[pneg]; + sum += num[ppos]; + + for(int i = pneg + 1; i < ppos; i++){ + if(num[i] + sum == 0){ + found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); + + break; + } + } + + int old = num[pneg]; + while(pneg < ppos && num[pneg] == old) pneg++; + } + + pneg = 0; + + int old = num[ppos]; + while(ppos > 0 && num[ppos] == old) ppos--; + } + + + return found; + + } +} diff --git a/_includes/_root/4sum/Solution.java b/_includes/_root/4sum/Solution.java index 5b372d9..2992b72 100644 --- a/_includes/_root/4sum/Solution.java +++ b/_includes/_root/4sum/Solution.java @@ -1,83 +1,83 @@ -public class Solution { - - static class TwoSum { - int index1; - int index2; - - boolean overlap(TwoSum other){ - if(this == other) return true; - - if(index1 == other.index1) return true; - if(index2 == other.index1) return true; - - if(index1 == other.index2) return true; - if(index2 == other.index2) return true; - - return false; - } - } - - public List> fourSum(int[] num, int target) { - ArrayList> found = new ArrayList>(); - - if(num.length < 4) return found; - - HashMap> cache = new HashMap>(); - - Arrays.sort(num); - - for(int i = 0; i < num.length; i++){ - for(int j = i + 1; j < num.length; j++){ - - int s = num[i] + num[j]; - TwoSum t = new TwoSum(); - - t.index1 = i; - t.index2 = j; - - ArrayList l = cache.get(s); - if(l == null){ - l = new ArrayList(); - cache.put(s, l); - } - - l.add(t); - } - } - - HashSet block = new HashSet(); - - for(Integer a : cache.keySet()){ - Integer b = target - a; - - ArrayList lsb = cache.get(b); - if(lsb != null){ - ArrayList lsa = cache.get(a); - - for(TwoSum sa : lsa) - for(TwoSum sb : lsb){ - - if(sa.overlap(sb)) continue; - - Integer[] sol = new Integer[]{num[sa.index1], num[sa.index2], num[sb.index1], num[sb.index2]}; - Arrays.sort(sol); - - String uid = Arrays.toString(sol); - if(!block.contains(uid)){ - found.add(Arrays.asList(sol)); - - block.add(uid); - } - - - } - - cache.put(a, null); - cache.put(b, null); - } - } - - - return found; - } -} +public class Solution { + + static class TwoSum { + int index1; + int index2; + + boolean overlap(TwoSum other){ + if(this == other) return true; + + if(index1 == other.index1) return true; + if(index2 == other.index1) return true; + + if(index1 == other.index2) return true; + if(index2 == other.index2) return true; + + return false; + } + } + + public List> fourSum(int[] num, int target) { + ArrayList> found = new ArrayList>(); + + if(num.length < 4) return found; + + HashMap> cache = new HashMap>(); + + Arrays.sort(num); + + for(int i = 0; i < num.length; i++){ + for(int j = i + 1; j < num.length; j++){ + + int s = num[i] + num[j]; + TwoSum t = new TwoSum(); + + t.index1 = i; + t.index2 = j; + + ArrayList l = cache.get(s); + if(l == null){ + l = new ArrayList(); + cache.put(s, l); + } + + l.add(t); + } + } + + HashSet block = new HashSet(); + + for(Integer a : cache.keySet()){ + Integer b = target - a; + + ArrayList lsb = cache.get(b); + if(lsb != null){ + ArrayList lsa = cache.get(a); + + for(TwoSum sa : lsa) + for(TwoSum sb : lsb){ + + if(sa.overlap(sb)) continue; + + Integer[] sol = new Integer[]{num[sa.index1], num[sa.index2], num[sb.index1], num[sb.index2]}; + Arrays.sort(sol); + + String uid = Arrays.toString(sol); + if(!block.contains(uid)){ + found.add(Arrays.asList(sol)); + + block.add(uid); + } + + + } + + cache.put(a, null); + cache.put(b, null); + } + } + + + return found; + } +} diff --git a/_includes/_root/add-binary/Solution.java b/_includes/_root/add-binary/Solution.java index d4b94b1..31c8933 100644 --- a/_includes/_root/add-binary/Solution.java +++ b/_includes/_root/add-binary/Solution.java @@ -1,47 +1,47 @@ -public class Solution { - - int toint(char c){ - if(c >= '0') return c - '0'; - return 0; - } - - int toint(char[] chars, int index){ - if(index < chars.length && index >=0 ) return toint(chars[index]); - return 0; - } - - public String addBinary(String a, String b) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(a == null || b == null) return null; - - char[] ca = a.toCharArray(); - char[] cb = b.toCharArray(); - - int n = Math.max(ca.length, cb.length); - - int[] s = new int[n + 1]; - - - //ca = Arrays.copyOf(ca , n); - //cb = Arrays.copyOf(cb , n); - - for(int i = 0 ; i=0; i--){ - ss = ss + s[i]; - } - - if ( s[n] == 1 ) ss = "1" + ss; - - return ss; - - } +public class Solution { + + int toint(char c){ + if(c >= '0') return c - '0'; + return 0; + } + + int toint(char[] chars, int index){ + if(index < chars.length && index >=0 ) return toint(chars[index]); + return 0; + } + + public String addBinary(String a, String b) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(a == null || b == null) return null; + + char[] ca = a.toCharArray(); + char[] cb = b.toCharArray(); + + int n = Math.max(ca.length, cb.length); + + int[] s = new int[n + 1]; + + + //ca = Arrays.copyOf(ca , n); + //cb = Arrays.copyOf(cb , n); + + for(int i = 0 ; i=0; i--){ + ss = ss + s[i]; + } + + if ( s[n] == 1 ) ss = "1" + ss; + + return ss; + + } } \ No newline at end of file diff --git a/_includes/_root/add-two-numbers/Solution.java b/_includes/_root/add-two-numbers/Solution.java index d8b1cbe..c66f5d7 100644 --- a/_includes/_root/add-two-numbers/Solution.java +++ b/_includes/_root/add-two-numbers/Solution.java @@ -1,50 +1,50 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - ListNode r = new ListNode(0); - ListNode h = r; - ListNode beforeend = r; - - while(l1 !=null && l2 != null){ - r.val += l1.val + l2.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - l1 = l1.next; - l2 = l2.next; - } - - ListNode rest; - if (l1 == null) rest = l2; else rest = l1; - - while(rest != null){ - r.val += rest.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - rest = rest.next; - } - - if(beforeend.next != null && beforeend.next.val == 0) beforeend.next = null; - - return h; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + ListNode r = new ListNode(0); + ListNode h = r; + ListNode beforeend = r; + + while(l1 !=null && l2 != null){ + r.val += l1.val + l2.val; + + r.next = new ListNode(r.val / 10); + r.val %= 10; + + beforeend = r; + r = r.next; + l1 = l1.next; + l2 = l2.next; + } + + ListNode rest; + if (l1 == null) rest = l2; else rest = l1; + + while(rest != null){ + r.val += rest.val; + + r.next = new ListNode(r.val / 10); + r.val %= 10; + + beforeend = r; + r = r.next; + rest = rest.next; + } + + if(beforeend.next != null && beforeend.next.val == 0) beforeend.next = null; + + return h; + } } \ No newline at end of file diff --git a/_includes/_root/anagrams/Solution.java b/_includes/_root/anagrams/Solution.java index f351a86..4bea62c 100644 --- a/_includes/_root/anagrams/Solution.java +++ b/_includes/_root/anagrams/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public ArrayList anagrams(String[] strs) { - ArrayList found = new ArrayList(); - - HashMap> box = new HashMap>(); - - for(String str : strs){ - char[] cstr = str.toCharArray(); - Arrays.sort(cstr); - - String key = new String(cstr); - - ArrayList c = box.get(key); - if(c == null){ - box.put(key , new ArrayList()); - } - - c = box.get(key); - c.add(str); - - } - - for(ArrayList s : box.values()){ - - if(s.size() > 1){ - found.addAll(s); - } - - } - - return found; - } +public class Solution { + public ArrayList anagrams(String[] strs) { + ArrayList found = new ArrayList(); + + HashMap> box = new HashMap>(); + + for(String str : strs){ + char[] cstr = str.toCharArray(); + Arrays.sort(cstr); + + String key = new String(cstr); + + ArrayList c = box.get(key); + if(c == null){ + box.put(key , new ArrayList()); + } + + c = box.get(key); + c.add(str); + + } + + for(ArrayList s : box.values()){ + + if(s.size() > 1){ + found.addAll(s); + } + + } + + return found; + } } \ No newline at end of file diff --git a/_includes/_root/balanced-binary-tree/Solution.java b/_includes/_root/balanced-binary-tree/Solution.java index 66881d4..9835271 100644 --- a/_includes/_root/balanced-binary-tree/Solution.java +++ b/_includes/_root/balanced-binary-tree/Solution.java @@ -1,30 +1,30 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int height(TreeNode root){ - if(root == null) - return 0; - else - return Math.max(height(root.left), height(root.right)) + 1; - } - - public boolean isBalanced(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(root == null) return true; - - return - Math.abs(height(root.left) - height(root.right)) <=1 && - isBalanced(root.left) && isBalanced(root.right); - - //return isBalanced() - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int height(TreeNode root){ + if(root == null) + return 0; + else + return Math.max(height(root.left), height(root.right)) + 1; + } + + public boolean isBalanced(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(root == null) return true; + + return + Math.abs(height(root.left) - height(root.right)) <=1 && + isBalanced(root.left) && isBalanced(root.right); + + //return isBalanced() + } } \ No newline at end of file diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java index 88f9adf..d037df7 100644 --- a/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java +++ b/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java @@ -1,24 +1,24 @@ -public class Solution { - public int maxProfit(int[] prices) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(prices.length <= 1) return 0; - - int profit = 0; - - int hold = prices[0]; - - for(int i = 1; i < prices.length; i++){ - - - if(hold < prices[i]){ - profit += prices[i] - hold; // sell - - } - - hold = prices[i]; - } - - return profit; - } +public class Solution { + public int maxProfit(int[] prices) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(prices.length <= 1) return 0; + + int profit = 0; + + int hold = prices[0]; + + for(int i = 1; i < prices.length; i++){ + + + if(hold < prices[i]){ + profit += prices[i] - hold; // sell + + } + + hold = prices[i]; + } + + return profit; + } } \ No newline at end of file diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java index c9702ba..29c2e8c 100644 --- a/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java +++ b/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int maxProfit(int[] prices) { - if(prices.length < 2) return 0; - - int[] left = new int[prices.length]; - int[] right = new int[prices.length]; - - - int left_min = prices[0]; - - for(int i = 1; i < prices.length; i++){ - left_min = Math.min(left_min, prices[i]); - left[i] = Math.max(prices[i] - left_min, left[i - 1]); - } - - int right_max = prices[prices.length - 1]; - - for(int i = prices.length - 2; i >= 0; i--){ - right_max = Math.max(right_max, prices[i]); - right[i] = Math.max(right_max - prices[i], right[i + 1]); - } - - int m = 0; - - for(int i = 0; i < prices.length; i++){ - m = Math.max(m, left[i] + right[i]); - } - - return m; - - } -} +public class Solution { + public int maxProfit(int[] prices) { + if(prices.length < 2) return 0; + + int[] left = new int[prices.length]; + int[] right = new int[prices.length]; + + + int left_min = prices[0]; + + for(int i = 1; i < prices.length; i++){ + left_min = Math.min(left_min, prices[i]); + left[i] = Math.max(prices[i] - left_min, left[i - 1]); + } + + int right_max = prices[prices.length - 1]; + + for(int i = prices.length - 2; i >= 0; i--){ + right_max = Math.max(right_max, prices[i]); + right[i] = Math.max(right_max - prices[i], right[i + 1]); + } + + int m = 0; + + for(int i = 0; i < prices.length; i++){ + m = Math.max(m, left[i] + right[i]); + } + + return m; + + } +} diff --git a/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java index 6b199ea..78e581c 100644 --- a/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java +++ b/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public int maxProfit(int[] prices) { - - int max = 0; - - int lowest = Integer.MAX_VALUE; - - for(int p : prices){ - - lowest = Math.min(lowest, p); - - max = Math.max(p - lowest, max); - } - - return max; - } -} +public class Solution { + public int maxProfit(int[] prices) { + + int max = 0; + + int lowest = Integer.MAX_VALUE; + + for(int p : prices){ + + lowest = Math.min(lowest, p); + + max = Math.max(p - lowest, max); + } + + return max; + } +} diff --git a/_includes/_root/binary-tree-inorder-traversal/Solution.java b/_includes/_root/binary-tree-inorder-traversal/Solution.java index f204104..9a01a4a 100644 --- a/_includes/_root/binary-tree-inorder-traversal/Solution.java +++ b/_includes/_root/binary-tree-inorder-traversal/Solution.java @@ -1,68 +1,68 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList inorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - rt.add(current.param.val); - - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList inorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + + rt.add(current.param.val); + + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + default: + break; + } + } + + + return rt; + } +} diff --git a/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java b/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java index 65cf4ce..de6dea7 100644 --- a/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java +++ b/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java @@ -1,46 +1,46 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrderBottom(TreeNode root) { - LinkedList> rt = new LinkedList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.push(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> levelOrderBottom(TreeNode root) { + LinkedList> rt = new LinkedList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + ArrayList level = new ArrayList(); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + rt.push(new ArrayList(level)); // copy + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node.val); + + if(node.left != null) queue.addLast(node.left); + if(node.right != null) queue.addLast(node.right); + } + } + + return rt; + } +} diff --git a/_includes/_root/binary-tree-level-order-traversal/Solution.java b/_includes/_root/binary-tree-level-order-traversal/Solution.java index 770d2e8..714da2d 100644 --- a/_includes/_root/binary-tree-level-order-traversal/Solution.java +++ b/_includes/_root/binary-tree-level-order-traversal/Solution.java @@ -1,48 +1,48 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.add(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> levelOrder(TreeNode root) { + + ArrayList> rt = new ArrayList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + ArrayList level = new ArrayList(); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + rt.add(new ArrayList(level)); // copy + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node.val); + + if(node.left != null) queue.addLast(node.left); + if(node.right != null) queue.addLast(node.right); + } + } + + return rt; + + } +} diff --git a/_includes/_root/binary-tree-maximum-path-sum/Solution.java b/_includes/_root/binary-tree-maximum-path-sum/Solution.java index a13e12e..fca1696 100644 --- a/_includes/_root/binary-tree-maximum-path-sum/Solution.java +++ b/_includes/_root/binary-tree-maximum-path-sum/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int max; - - int sum(TreeNode root){ - if(root == null) return 0; - - int left = sum(root.left); - int right = sum(root.right); - - left = Math.max(left, 0); - right = Math.max(right, 0); - - int sum = root.val + left + right; - max = Math.max(max, sum); - - return Math.max(left, right) + root.val; - } - - public int maxPathSum(TreeNode root) { - - max = Integer.MIN_VALUE; - sum(root); - - return max; - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int max; + + int sum(TreeNode root){ + if(root == null) return 0; + + int left = sum(root.left); + int right = sum(root.right); + + left = Math.max(left, 0); + right = Math.max(right, 0); + + int sum = root.val + left + right; + max = Math.max(max, sum); + + return Math.max(left, right) + root.val; + } + + public int maxPathSum(TreeNode root) { + + max = Integer.MIN_VALUE; + sum(root); + + return max; + } } \ No newline at end of file diff --git a/_includes/_root/binary-tree-postorder-traversal/Solution.java b/_includes/_root/binary-tree-postorder-traversal/Solution.java index f2ae0df..989a06e 100644 --- a/_includes/_root/binary-tree-postorder-traversal/Solution.java +++ b/_includes/_root/binary-tree-postorder-traversal/Solution.java @@ -1,69 +1,69 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList postorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - - case POST: - current.returnAddress = ReturnAddress.DONE; - - rt.add(current.param.val); - - default: - break; - } - } - - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList postorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + + case POST: + current.returnAddress = ReturnAddress.DONE; + + rt.add(current.param.val); + + default: + break; + } + } + + + return rt; + } +} diff --git a/_includes/_root/binary-tree-preorder-traversal/Solution.java b/_includes/_root/binary-tree-preorder-traversal/Solution.java index a7c226d..6172150 100644 --- a/_includes/_root/binary-tree-preorder-traversal/Solution.java +++ b/_includes/_root/binary-tree-preorder-traversal/Solution.java @@ -1,68 +1,68 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList preorderTraversal(TreeNode root) { - - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - rt.add(current.param.val); - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList preorderTraversal(TreeNode root) { + + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + rt.add(current.param.val); + + case IN: + current.returnAddress = ReturnAddress.POST; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + default: + break; + } + } + + + return rt; + + } +} diff --git a/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java b/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java index be4e694..b20f5f2 100644 --- a/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java +++ b/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java @@ -1,58 +1,58 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> zigzagLevelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - boolean direction = true; // true for left -> right , false for right -> left - - Deque level = new LinkedList(); - - while(!queue.isEmpty()){ - TreeNode current = queue.poll(); - - if(current == END){ - - direction = !direction; - rt.add(new ArrayList(level)); // copy - - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - if(direction){ // true for left -> right , false for right -> left - level.addLast(current.val); - }else{ - level.addFirst(current.val); - } - - - if(current.left != null) queue.add(current.left); - if(current.right != null) queue.add(current.right); - - } - } - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> zigzagLevelOrder(TreeNode root) { + + ArrayList> rt = new ArrayList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + boolean direction = true; // true for left -> right , false for right -> left + + Deque level = new LinkedList(); + + while(!queue.isEmpty()){ + TreeNode current = queue.poll(); + + if(current == END){ + + direction = !direction; + rt.add(new ArrayList(level)); // copy + + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + if(direction){ // true for left -> right , false for right -> left + level.addLast(current.val); + }else{ + level.addFirst(current.val); + } + + + if(current.left != null) queue.add(current.left); + if(current.right != null) queue.add(current.right); + + } + } + + return rt; + + } +} diff --git a/_includes/_root/candy/Solution.java b/_includes/_root/candy/Solution.java index 0a35b14..1de13ae 100644 --- a/_includes/_root/candy/Solution.java +++ b/_includes/_root/candy/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public int candy(int[] ratings) { - - - int[] candies = new int[ratings.length]; - - Arrays.fill(candies, 1); - - for(int i = 1; i < candies.length; i++){ - if(ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) - candies[i] = candies[i - 1] + 1; - } - - for(int i = candies.length - 2; i >= 0; i--){ - if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) - candies[i] = candies[i + 1] + 1; - } - - int s = 0; - for(int c : candies) - s += c; - - return s; - - } +public class Solution { + public int candy(int[] ratings) { + + + int[] candies = new int[ratings.length]; + + Arrays.fill(candies, 1); + + for(int i = 1; i < candies.length; i++){ + if(ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) + candies[i] = candies[i - 1] + 1; + } + + for(int i = candies.length - 2; i >= 0; i--){ + if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) + candies[i] = candies[i + 1] + 1; + } + + int s = 0; + for(int c : candies) + s += c; + + return s; + + } } \ No newline at end of file diff --git a/_includes/_root/climbing-stairs/Solution.java b/_includes/_root/climbing-stairs/Solution.java index 75980e3..8706e30 100644 --- a/_includes/_root/climbing-stairs/Solution.java +++ b/_includes/_root/climbing-stairs/Solution.java @@ -1,19 +1,19 @@ -public class Solution { - public int climbStairs(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - int[] step = new int[Math.max(n + 1, 3)]; - - - step[0] = 0; - step[1] = 1; - step[2] = 2; - - for(int i = 3; i <= n; i++){ - step[i] = step[i - 1] + step[i - 2]; - } - - return step[n]; - } +public class Solution { + public int climbStairs(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + int[] step = new int[Math.max(n + 1, 3)]; + + + step[0] = 0; + step[1] = 1; + step[2] = 2; + + for(int i = 3; i <= n; i++){ + step[i] = step[i - 1] + step[i - 2]; + } + + return step[n]; + } } \ No newline at end of file diff --git a/_includes/_root/clone-graph/Solution.java b/_includes/_root/clone-graph/Solution.java index bf42b80..11a8222 100644 --- a/_includes/_root/clone-graph/Solution.java +++ b/_includes/_root/clone-graph/Solution.java @@ -1,54 +1,54 @@ -/** - * Definition for undirected graph. - * class UndirectedGraphNode { - * int label; - * ArrayList neighbors; - * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } - * }; - */ -public class Solution { - public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { - - if(node == null) return null; - - // visit - HashMap clone = new HashMap(); - - Deque queue = new LinkedList(); - - queue.add(node); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!clone.containsKey(n)){ - clone.put(n, new UndirectedGraphNode(n.label)); - - for(UndirectedGraphNode neighbor : n.neighbors){ - queue.add(neighbor); - } - } - } - - queue.add(node); - HashSet visit = new HashSet(); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!visit.contains(n)){ - visit.add(n); - - UndirectedGraphNode c = clone.get(n); - - for(UndirectedGraphNode neighbor : n.neighbors){ - c.neighbors.add(clone.get(neighbor)); - queue.add(neighbor); - } - } - } - - return clone.get(node); - - } +/** + * Definition for undirected graph. + * class UndirectedGraphNode { + * int label; + * ArrayList neighbors; + * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } + * }; + */ +public class Solution { + public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { + + if(node == null) return null; + + // visit + HashMap clone = new HashMap(); + + Deque queue = new LinkedList(); + + queue.add(node); + + while(queue.size() > 0){ + + UndirectedGraphNode n = queue.poll(); + if(!clone.containsKey(n)){ + clone.put(n, new UndirectedGraphNode(n.label)); + + for(UndirectedGraphNode neighbor : n.neighbors){ + queue.add(neighbor); + } + } + } + + queue.add(node); + HashSet visit = new HashSet(); + + while(queue.size() > 0){ + + UndirectedGraphNode n = queue.poll(); + if(!visit.contains(n)){ + visit.add(n); + + UndirectedGraphNode c = clone.get(n); + + for(UndirectedGraphNode neighbor : n.neighbors){ + c.neighbors.add(clone.get(neighbor)); + queue.add(neighbor); + } + } + } + + return clone.get(node); + + } } \ No newline at end of file diff --git a/_includes/_root/combination-sum-ii/Solution.java b/_includes/_root/combination-sum-ii/Solution.java index b4409da..c3b2627 100644 --- a/_includes/_root/combination-sum-ii/Solution.java +++ b/_includes/_root/combination-sum-ii/Solution.java @@ -1,63 +1,63 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - HashSet block; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - String uid = found.toString(); - - if(!block.contains(uid)){ - rt.add(found); - block.add(uid); - } - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target && i <= 1; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - public List> combinationSum2(int[] num, int target) { - Arrays.sort(num); - - candidates = num; - this.target = target; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - block = new HashSet(); - - search(0, 0); - - return rt; - - } -} +public class Solution { + int target; + + int[] candidates; + + int[] stack; + + ArrayList> rt; + + HashSet block; + + void search(int sp, int cur){ + + if(cur == target){ + ArrayList found = new ArrayList(); + for(int i = 0; i < stack.length; i++){ + for(int j = 0; j < stack[i]; j++){ + found.add(candidates[i]); + } + } + + String uid = found.toString(); + + if(!block.contains(uid)){ + rt.add(found); + block.add(uid); + } + return; + + } + + if(sp >= stack.length){ + return; + } + + int toadd = candidates[sp]; + + for(int i = 0; cur + toadd * i <= target && i <= 1; i++ ){ + stack[sp] = i; + search(sp + 1, cur + toadd * i); + stack[sp] = 0; + } + + } + + public List> combinationSum2(int[] num, int target) { + Arrays.sort(num); + + candidates = num; + this.target = target; + + stack = new int[candidates.length]; + + rt = new ArrayList>(); + + block = new HashSet(); + + search(0, 0); + + return rt; + + } +} diff --git a/_includes/_root/combination-sum/Solution.java b/_includes/_root/combination-sum/Solution.java index b93dc1f..7bb1278 100644 --- a/_includes/_root/combination-sum/Solution.java +++ b/_includes/_root/combination-sum/Solution.java @@ -1,56 +1,56 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - rt.add(found); - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - - public List> combinationSum(int[] candidates, int target) { - Arrays.sort(candidates); - - this.target = target; - - this.candidates = candidates; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - search(0, 0); - - return rt; - - } -} +public class Solution { + int target; + + int[] candidates; + + int[] stack; + + ArrayList> rt; + + void search(int sp, int cur){ + + if(cur == target){ + ArrayList found = new ArrayList(); + for(int i = 0; i < stack.length; i++){ + for(int j = 0; j < stack[i]; j++){ + found.add(candidates[i]); + } + } + + rt.add(found); + return; + + } + + if(sp >= stack.length){ + return; + } + + int toadd = candidates[sp]; + + for(int i = 0; cur + toadd * i <= target; i++ ){ + stack[sp] = i; + search(sp + 1, cur + toadd * i); + stack[sp] = 0; + } + + } + + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + + this.target = target; + + this.candidates = candidates; + + stack = new int[candidates.length]; + + rt = new ArrayList>(); + + search(0, 0); + + return rt; + + } +} diff --git a/_includes/_root/combinations/Solution.java b/_includes/_root/combinations/Solution.java index d4e83cc..83fdc3c 100644 --- a/_includes/_root/combinations/Solution.java +++ b/_includes/_root/combinations/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - - Integer[] num; - Integer[] stack; - int target; - - ArrayList> found; - - - void search(int p){ - if(p == target){ - found.add(new ArrayList(Arrays.asList(stack))); - return; - } - - for(Integer n : num){ - if(p > 0 && n <= stack[p - 1]) continue; - - stack[p] = n; - search(p + 1); - } - } - - public List> combine(int n, int k) { - - target = k; - - num = new Integer[n]; - for(int i = 1; i <= n; i++) num[i - 1] = i; - - stack = new Integer[k]; - - found = new ArrayList>(); - - search(0); - - return found; - } -} +public class Solution { + + Integer[] num; + Integer[] stack; + int target; + + ArrayList> found; + + + void search(int p){ + if(p == target){ + found.add(new ArrayList(Arrays.asList(stack))); + return; + } + + for(Integer n : num){ + if(p > 0 && n <= stack[p - 1]) continue; + + stack[p] = n; + search(p + 1); + } + } + + public List> combine(int n, int k) { + + target = k; + + num = new Integer[n]; + for(int i = 1; i <= n; i++) num[i - 1] = i; + + stack = new Integer[k]; + + found = new ArrayList>(); + + search(0); + + return found; + } +} diff --git a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java b/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java index 667fece..0bdc2db 100644 --- a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java +++ b/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java @@ -1,40 +1,40 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int[] inorder; - int[] postorder; - int p; - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; - - TreeNode root = new TreeNode(postorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != postorder[p] ; i++); - - p--; - root.right = buildTree(i + 1, ed); - root.left = buildTree(st, i); - - return root; - } - - public TreeNode buildTree(int[] inorder, int[] postorder) { - - this.p = postorder.length - 1; - this.inorder = inorder; - this.postorder = postorder; - - return buildTree(0, inorder.length); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int[] inorder; + int[] postorder; + int p; + + TreeNode buildTree(int st, int ed){ + + if(st >= ed) return null; + + TreeNode root = new TreeNode(postorder[p]); + + int i; + for(i = st ; i< ed && inorder[i] != postorder[p] ; i++); + + p--; + root.right = buildTree(i + 1, ed); + root.left = buildTree(st, i); + + return root; + } + + public TreeNode buildTree(int[] inorder, int[] postorder) { + + this.p = postorder.length - 1; + this.inorder = inorder; + this.postorder = postorder; + + return buildTree(0, inorder.length); + } } \ No newline at end of file diff --git a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java b/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java index d807911..ead52a6 100644 --- a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java +++ b/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java @@ -1,44 +1,44 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int p = 0; - int[] preorder; - int[] inorder; - - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; // - - TreeNode root = new TreeNode(preorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != preorder[p] ; i++); - - p++; - root.left = buildTree(st, i); - root.right = buildTree(i + 1, ed); - - return root; - } - - - public TreeNode buildTree(int[] preorder, int[] inorder) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - this.preorder = preorder; - this.inorder = inorder; - this.p = 0; - //if (preorder.length == 0) return null; - return buildTree(0 , inorder.length); - //return new TreeNode(preorder[p]); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int p = 0; + int[] preorder; + int[] inorder; + + + TreeNode buildTree(int st, int ed){ + + if(st >= ed) return null; // + + TreeNode root = new TreeNode(preorder[p]); + + int i; + for(i = st ; i< ed && inorder[i] != preorder[p] ; i++); + + p++; + root.left = buildTree(st, i); + root.right = buildTree(i + 1, ed); + + return root; + } + + + public TreeNode buildTree(int[] preorder, int[] inorder) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + this.preorder = preorder; + this.inorder = inorder; + this.p = 0; + //if (preorder.length == 0) return null; + return buildTree(0 , inorder.length); + //return new TreeNode(preorder[p]); + } } \ No newline at end of file diff --git a/_includes/_root/container-with-most-water/Solution.java b/_includes/_root/container-with-most-water/Solution.java index 6d31f32..f697152 100644 --- a/_includes/_root/container-with-most-water/Solution.java +++ b/_includes/_root/container-with-most-water/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int maxArea(int[] height) { - - if(height.length <= 1) return 0; - - - int st = 0; - int ed = height.length - 1; - - - int max = Integer.MIN_VALUE; - - while(st < ed){ - - int current = Math.min(height[st] , height[ed]) * (ed - st); - - if(current > max) max = current; - - if(height[st] <= height[ed]){ - st++; - }else{ - ed--; - } - - - } - - - return max; - - } +public class Solution { + public int maxArea(int[] height) { + + if(height.length <= 1) return 0; + + + int st = 0; + int ed = height.length - 1; + + + int max = Integer.MIN_VALUE; + + while(st < ed){ + + int current = Math.min(height[st] , height[ed]) * (ed - st); + + if(current > max) max = current; + + if(height[st] <= height[ed]){ + st++; + }else{ + ed--; + } + + + } + + + return max; + + } } \ No newline at end of file diff --git a/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java b/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java index eee1c66..7c899fa 100644 --- a/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java +++ b/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java @@ -1,32 +1,32 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - //TreeNode - - public TreeNode sortedArrayToBST(int[] num) { - - if(num.length == 0) - return null; - - if(num.length == 1) - return new TreeNode(num[0]); - - int mid = num.length / 2; - - TreeNode root = new TreeNode(num[mid]); - - root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); - root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, num.length)); - - return root; - - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + //TreeNode + + public TreeNode sortedArrayToBST(int[] num) { + + if(num.length == 0) + return null; + + if(num.length == 1) + return new TreeNode(num[0]); + + int mid = num.length / 2; + + TreeNode root = new TreeNode(num[mid]); + + root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); + root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, num.length)); + + return root; + + } } \ No newline at end of file diff --git a/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java b/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java index 7e5fb38..ded690f 100644 --- a/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java +++ b/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java @@ -1,53 +1,53 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; next = null; } - * } - */ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - ListNode cutatmid(ListNode head){ - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - ListNode pslow = head; - - while(fast != null && fast.next != null){ - pslow = slow; - slow = slow.next; - fast = fast.next.next; - } - - pslow.next = null; - return slow; - } - - public TreeNode sortedListToBST(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - if(head.next == null) return new TreeNode(head.val); - - ListNode mid = cutatmid(head); - - TreeNode root = new TreeNode(mid.val); - root.left = sortedListToBST(head); - root.right = sortedListToBST(mid.next); - - return root; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; next = null; } + * } + */ +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + ListNode cutatmid(ListNode head){ + if(head == null) return null; + + ListNode fast = head; + ListNode slow = head; + ListNode pslow = head; + + while(fast != null && fast.next != null){ + pslow = slow; + slow = slow.next; + fast = fast.next.next; + } + + pslow.next = null; + return slow; + } + + public TreeNode sortedListToBST(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + if(head.next == null) return new TreeNode(head.val); + + ListNode mid = cutatmid(head); + + TreeNode root = new TreeNode(mid.val); + root.left = sortedListToBST(head); + root.right = sortedListToBST(mid.next); + + return root; + } } \ No newline at end of file diff --git a/_includes/_root/copy-list-with-random-pointer/Solution.java b/_includes/_root/copy-list-with-random-pointer/Solution.java index 626260e..947fd8d 100644 --- a/_includes/_root/copy-list-with-random-pointer/Solution.java +++ b/_includes/_root/copy-list-with-random-pointer/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for singly-linked list with a random pointer. - * class RandomListNode { - * int label; - * RandomListNode next, random; - * RandomListNode(int x) { this.label = x; } - * }; - */ -public class Solution { - public RandomListNode copyRandomList(RandomListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - HashMap map = new HashMap(); - - RandomListNode iter = head; - while(iter != null){ - RandomListNode born = new RandomListNode(iter.label); - map.put(iter, born); - - iter = iter.next; - } - - iter = head; - - while(iter != null){ - RandomListNode islet = map.get(iter); - - islet.next = map.get(iter.next); - islet.random = map.get(iter.random); - - iter = iter.next; - } - - return map.get(head); - } +/** + * Definition for singly-linked list with a random pointer. + * class RandomListNode { + * int label; + * RandomListNode next, random; + * RandomListNode(int x) { this.label = x; } + * }; + */ +public class Solution { + public RandomListNode copyRandomList(RandomListNode head) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + + HashMap map = new HashMap(); + + RandomListNode iter = head; + while(iter != null){ + RandomListNode born = new RandomListNode(iter.label); + map.put(iter, born); + + iter = iter.next; + } + + iter = head; + + while(iter != null){ + RandomListNode islet = map.get(iter); + + islet.next = map.get(iter.next); + islet.random = map.get(iter.random); + + iter = iter.next; + } + + return map.get(head); + } } \ No newline at end of file diff --git a/_includes/_root/count-and-say/Solution.java b/_includes/_root/count-and-say/Solution.java index ac820c4..d8c902a 100644 --- a/_includes/_root/count-and-say/Solution.java +++ b/_includes/_root/count-and-say/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - String countAndSay(String prev){ - - char[] str = prev.toCharArray(); - - int p = 1; - int count = 1; - char last = str[0]; - - String s = ""; - - while(p < str.length){ - - if(str[p] == last){ - count++; - - }else{ - - s += "" + count + last; - - last = str[p]; - count = 1; - } - - p++; - } - - s += "" + count + last; - - return s; - } - - public String countAndSay(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - String init = "1"; - - for(int i = 0; i < n - 1; i++){ - init = countAndSay(init); - } - - return init; - - } +public class Solution { + + String countAndSay(String prev){ + + char[] str = prev.toCharArray(); + + int p = 1; + int count = 1; + char last = str[0]; + + String s = ""; + + while(p < str.length){ + + if(str[p] == last){ + count++; + + }else{ + + s += "" + count + last; + + last = str[p]; + count = 1; + } + + p++; + } + + s += "" + count + last; + + return s; + } + + public String countAndSay(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + String init = "1"; + + for(int i = 0; i < n - 1; i++){ + init = countAndSay(init); + } + + return init; + + } } \ No newline at end of file diff --git a/_includes/_root/decode-ways/Solution.java b/_includes/_root/decode-ways/Solution.java index 5c2657d..ea87fa8 100644 --- a/_includes/_root/decode-ways/Solution.java +++ b/_includes/_root/decode-ways/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - - public int numDecodings(String s) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - final char[] _s = s.toCharArray(); - final int n = _s.length; - - if (n == 0 ) return 0; - - int[] step = new int[Math.max(n + 1, 3)]; - - step[0] = 1; - - step[1] = 0; - - if(_s[0] != '0') - step[1] = 1; - - for(int i = 2; i <= n; i++){ - - step[i] = 0; - - if ( _s[i - 1] != '0' ){ - step[i] += step[i - 1]; - } - - if ( _s[i - 2] != '0' ){ - if ( (_s[i - 2] - '0') * 10 + (_s[i - 1] - '0') <= 26 ) - step[i] += step[i - 2]; - } - - } - - return step[n]; - } - +public class Solution { + + public int numDecodings(String s) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + final char[] _s = s.toCharArray(); + final int n = _s.length; + + if (n == 0 ) return 0; + + int[] step = new int[Math.max(n + 1, 3)]; + + step[0] = 1; + + step[1] = 0; + + if(_s[0] != '0') + step[1] = 1; + + for(int i = 2; i <= n; i++){ + + step[i] = 0; + + if ( _s[i - 1] != '0' ){ + step[i] += step[i - 1]; + } + + if ( _s[i - 2] != '0' ){ + if ( (_s[i - 2] - '0') * 10 + (_s[i - 1] - '0') <= 26 ) + step[i] += step[i - 2]; + } + + } + + return step[n]; + } + } \ No newline at end of file diff --git a/_includes/_root/distinct-subsequences/Solution.java b/_includes/_root/distinct-subsequences/Solution.java index 1edb247..54077ac 100644 --- a/_includes/_root/distinct-subsequences/Solution.java +++ b/_includes/_root/distinct-subsequences/Solution.java @@ -1,50 +1,50 @@ -public class Solution { - public int numDistinct(String S, String T) { - - - char[] s = S.toCharArray(); - if(s.length == 0) return 0; - - char[] t = T.toCharArray(); - if(t.length == 0) return 0; - - if(t.length > s.length) return 0; - - - int[][] P = new int[s.length][t.length]; - - - P[0][0] = s[0] == t[0] ? 1 : 0; - - for(int i = 1; i < s.length; i++){ - P[i][0] = s[i] == t[0] ? 1 + P[i - 1][0] : P[i - 1][0]; - } - - - for(int j = 1; j < t.length; j++){ - for(int i = j; i < s.length; i++){ - - if(t[j] == s[i]){ - // sum choices - - P[i][j] = P[i - 1][j] + P[i - 1][j - 1]; - - - } else { - // no choice - P[i][j] = P[i - 1][j]; - - } - - - - - } - } - - - return P[s.length - 1][t.length - 1]; - - - } +public class Solution { + public int numDistinct(String S, String T) { + + + char[] s = S.toCharArray(); + if(s.length == 0) return 0; + + char[] t = T.toCharArray(); + if(t.length == 0) return 0; + + if(t.length > s.length) return 0; + + + int[][] P = new int[s.length][t.length]; + + + P[0][0] = s[0] == t[0] ? 1 : 0; + + for(int i = 1; i < s.length; i++){ + P[i][0] = s[i] == t[0] ? 1 + P[i - 1][0] : P[i - 1][0]; + } + + + for(int j = 1; j < t.length; j++){ + for(int i = j; i < s.length; i++){ + + if(t[j] == s[i]){ + // sum choices + + P[i][j] = P[i - 1][j] + P[i - 1][j - 1]; + + + } else { + // no choice + P[i][j] = P[i - 1][j]; + + } + + + + + } + } + + + return P[s.length - 1][t.length - 1]; + + + } } \ No newline at end of file diff --git a/_includes/_root/divide-two-integers/Solution.java b/_includes/_root/divide-two-integers/Solution.java index a08aa5f..8ca078a 100644 --- a/_includes/_root/divide-two-integers/Solution.java +++ b/_includes/_root/divide-two-integers/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int divide(int dividend, int divisor) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(dividend == 0) return 0; - - if(dividend == Integer.MIN_VALUE){ - if(divisor < 0) - return 1 + divide(dividend - divisor, divisor); - else - return 0 - (1 + 0 - divide((dividend + divisor), divisor)); - } - - if(divisor == Integer.MIN_VALUE){ - return dividend == divisor ? 1 : 0; - } - - if(dividend > 0 && divisor < 0) return 0 - divide(dividend, 0 - divisor); - if(dividend < 0 && divisor > 0) return 0 - divide(0 - dividend, divisor); - if(dividend < 0 && divisor < 0) return divide(0 - dividend, 0 - divisor); - - int quotient = 0; - int a = 1; - - int r = divisor; - - while(dividend >= divisor ){ - - if(r > dividend){ - a--; - r -= divisor; - }else{ - dividend -= r; - quotient += a++; - r += divisor; - } - } - - - - return quotient; - } -} +public class Solution { + public int divide(int dividend, int divisor) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(dividend == 0) return 0; + + if(dividend == Integer.MIN_VALUE){ + if(divisor < 0) + return 1 + divide(dividend - divisor, divisor); + else + return 0 - (1 + 0 - divide((dividend + divisor), divisor)); + } + + if(divisor == Integer.MIN_VALUE){ + return dividend == divisor ? 1 : 0; + } + + if(dividend > 0 && divisor < 0) return 0 - divide(dividend, 0 - divisor); + if(dividend < 0 && divisor > 0) return 0 - divide(0 - dividend, divisor); + if(dividend < 0 && divisor < 0) return divide(0 - dividend, 0 - divisor); + + int quotient = 0; + int a = 1; + + int r = divisor; + + while(dividend >= divisor ){ + + if(r > dividend){ + a--; + r -= divisor; + }else{ + dividend -= r; + quotient += a++; + r += divisor; + } + } + + + + return quotient; + } +} diff --git a/_includes/_root/edit-distance/Solution.java b/_includes/_root/edit-distance/Solution.java index 08fad30..97d9d43 100644 --- a/_includes/_root/edit-distance/Solution.java +++ b/_includes/_root/edit-distance/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - public int minDistance(String word1, String word2) { - - // http://en.wikipedia.org/wiki/Levenshtein_distance - - char[] w1 = word1.toCharArray(); - char[] w2 = word2.toCharArray(); - - - - int[][] P = new int[w1.length + 1][w2.length + 1]; - - int i, j; - - for(i = 1; i <= w1.length; i++){ - P[i][0] = i; - } - - for(j = 1; j <= w2.length; j++){ - P[0][j] = j; - } - - for(i = 1; i <= w1.length; i++){ - for(j = 1; j <= w2.length; j++){ - - P[i][j] = Math.min(P[i - 1][j], P[i][j - 1]) + 1; - - if(w1[i - 1] == w2[j - 1]){ - P[i][j] = Math.min(P[i - 1][j - 1], P[i][j]); - }else { - P[i][j] = Math.min(P[i - 1][j - 1] + 1, P[i][j]); - } - - } - } - - return P[w1.length][w2.length]; - } +public class Solution { + public int minDistance(String word1, String word2) { + + // http://en.wikipedia.org/wiki/Levenshtein_distance + + char[] w1 = word1.toCharArray(); + char[] w2 = word2.toCharArray(); + + + + int[][] P = new int[w1.length + 1][w2.length + 1]; + + int i, j; + + for(i = 1; i <= w1.length; i++){ + P[i][0] = i; + } + + for(j = 1; j <= w2.length; j++){ + P[0][j] = j; + } + + for(i = 1; i <= w1.length; i++){ + for(j = 1; j <= w2.length; j++){ + + P[i][j] = Math.min(P[i - 1][j], P[i][j - 1]) + 1; + + if(w1[i - 1] == w2[j - 1]){ + P[i][j] = Math.min(P[i - 1][j - 1], P[i][j]); + }else { + P[i][j] = Math.min(P[i - 1][j - 1] + 1, P[i][j]); + } + + } + } + + return P[w1.length][w2.length]; + } } \ No newline at end of file diff --git a/_includes/_root/evaluate-reverse-polish-notation/Solution.java b/_includes/_root/evaluate-reverse-polish-notation/Solution.java index ef627ab..e148b49 100644 --- a/_includes/_root/evaluate-reverse-polish-notation/Solution.java +++ b/_includes/_root/evaluate-reverse-polish-notation/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - public int evalRPN(String[] tokens) { - - final Deque stack = new LinkedList(); - - for(String t : tokens){ - if("+".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 + v2); - }else if("-".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 - v2); - }else if("*".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 * v2); - }else if("/".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 / v2); - }else{ - stack.push(Integer.valueOf(t)); - } - } - - return stack.pop(); - - } -} +public class Solution { + public int evalRPN(String[] tokens) { + + final Deque stack = new LinkedList(); + + for(String t : tokens){ + if("+".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 + v2); + }else if("-".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 - v2); + }else if("*".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 * v2); + }else if("/".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 / v2); + }else{ + stack.push(Integer.valueOf(t)); + } + } + + return stack.pop(); + + } +} diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java b/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java index 55e2b00..a43ffe6 100644 --- a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java +++ b/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java @@ -1,30 +1,30 @@ -public class Solution { - public int findMin(int[] num) { - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // bad case - if (num[s] == num[m] && num[m] == num[e - 1]){ - return Math.min(num[s], findMin(Arrays.copyOfRange(num, s + 1, e))); - } - - // s < m < e - if ( num[s] <= num[m] && num[m] <= num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] <= num[m] && num[m] >= num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - - } -} +public class Solution { + public int findMin(int[] num) { + if(num.length == 1) return num[0]; + if(num.length == 2) return Math.min(num[0], num[1]); + + int s = 0; + int e = num.length; + + int m = (s + e) / 2; + + // bad case + if (num[s] == num[m] && num[m] == num[e - 1]){ + return Math.min(num[s], findMin(Arrays.copyOfRange(num, s + 1, e))); + } + + // s < m < e + if ( num[s] <= num[m] && num[m] <= num[e - 1]){ + return num[s]; + } + + // s < m > e + if ( num[s] <= num[m] && num[m] >= num[e - 1]){ + return findMin(Arrays.copyOfRange(num, m, e)); + } + + // s > m < e + return findMin(Arrays.copyOfRange(num, s, m + 1)); + + } +} diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java b/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java index ae8b13f..f5527b2 100644 --- a/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java +++ b/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java @@ -1,25 +1,25 @@ -public class Solution { - public int findMin(int[] num) { - - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // s < m < e - if ( num[s] < num[m] && num[m] < num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] < num[m] && num[m] > num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - } -} +public class Solution { + public int findMin(int[] num) { + + if(num.length == 1) return num[0]; + if(num.length == 2) return Math.min(num[0], num[1]); + + int s = 0; + int e = num.length; + + int m = (s + e) / 2; + + // s < m < e + if ( num[s] < num[m] && num[m] < num[e - 1]){ + return num[s]; + } + + // s < m > e + if ( num[s] < num[m] && num[m] > num[e - 1]){ + return findMin(Arrays.copyOfRange(num, m, e)); + } + + // s > m < e + return findMin(Arrays.copyOfRange(num, s, m + 1)); + } +} diff --git a/_includes/_root/find-peak-element/README.md b/_includes/_root/find-peak-element/README.md index 6df33e1..e1528e4 100644 --- a/_includes/_root/find-peak-element/README.md +++ b/_includes/_root/find-peak-element/README.md @@ -1,11 +1,11 @@ -## logarithmic is a sign - -`O(lg n)` is something like `binary search` or `merge sort`. - - -``` -find-peak-element = first elemen only one element - index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise -``` - - +## logarithmic is a sign + +`O(lg n)` is something like `binary search` or `merge sort`. + + +``` +find-peak-element = first elemen only one element + index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise +``` + + diff --git a/_includes/_root/first-missing-positive/Solution.java b/_includes/_root/first-missing-positive/Solution.java index 988f30d..e61e2dc 100644 --- a/_includes/_root/first-missing-positive/Solution.java +++ b/_includes/_root/first-missing-positive/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public int firstMissingPositive(int[] A) { - - final int N = A.length; - - next: - for(int i = 0; i < N; i++){ - int v = A[i]; - - if(v == i + 1) continue ; - - while(true){ - if(v <= 0 || v > N){ - continue next; - } - - int t = A[v - 1]; - - if(t == v){ - continue next; - } - - A[v - 1] = v; - v = t; - } - - } - - for(int i = 0; i < N; i++){ - int v = A[i]; - - if (v != i + 1){ - return i + 1; - } - } - - return N + 1; - - } +public class Solution { + public int firstMissingPositive(int[] A) { + + final int N = A.length; + + next: + for(int i = 0; i < N; i++){ + int v = A[i]; + + if(v == i + 1) continue ; + + while(true){ + if(v <= 0 || v > N){ + continue next; + } + + int t = A[v - 1]; + + if(t == v){ + continue next; + } + + A[v - 1] = v; + v = t; + } + + } + + for(int i = 0; i < N; i++){ + int v = A[i]; + + if (v != i + 1){ + return i + 1; + } + } + + return N + 1; + + } } \ No newline at end of file diff --git a/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java b/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java index a7a9c1f..e1e416c 100644 --- a/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java +++ b/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java @@ -1,39 +1,39 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode prev; - - void preorder(TreeNode root){ - - if(root == null) return; - - TreeNode left = root.left; - TreeNode right = root.right; - - // root - if(prev != null){ - prev.right = root; - prev.left = null; - } - - prev = root; - - preorder(left); - preorder(right); - } - - - public void flatten(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - prev = null; - preorder(root); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode prev; + + void preorder(TreeNode root){ + + if(root == null) return; + + TreeNode left = root.left; + TreeNode right = root.right; + + // root + if(prev != null){ + prev.right = root; + prev.left = null; + } + + prev = root; + + preorder(left); + preorder(right); + } + + + public void flatten(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + prev = null; + preorder(root); + } } \ No newline at end of file diff --git a/_includes/_root/gas-station/Solution.java b/_includes/_root/gas-station/Solution.java index c4018fe..eebcb59 100644 --- a/_includes/_root/gas-station/Solution.java +++ b/_includes/_root/gas-station/Solution.java @@ -1,27 +1,27 @@ -public class Solution { - public int canCompleteCircuit(int[] gas, int[] cost) { - - - int start = 0; - int from_start = 0; - - int total = 0; - - for(int i = 0; i < gas.length; i++){ - int left = gas[i] - cost[i]; - total += left; - from_start += left; - - if(from_start < 0){ - from_start = 0; - start = i + 1; // restart from next station - } - } - - if(total >= 0){ - return start; - } - - return -1; - } +public class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + + + int start = 0; + int from_start = 0; + + int total = 0; + + for(int i = 0; i < gas.length; i++){ + int left = gas[i] - cost[i]; + total += left; + from_start += left; + + if(from_start < 0){ + from_start = 0; + start = i + 1; // restart from next station + } + } + + if(total >= 0){ + return start; + } + + return -1; + } } \ No newline at end of file diff --git a/_includes/_root/generate-parentheses/Solution.java b/_includes/_root/generate-parentheses/Solution.java index 45c1c96..26576e1 100644 --- a/_includes/_root/generate-parentheses/Solution.java +++ b/_includes/_root/generate-parentheses/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public List generateParenthesis(int n) { - - if (n == 0) return new ArrayList(); - if (n == 1) return Arrays.asList(new String[]{"()"}); - - HashSet temp = new HashSet(); - - for(String s : generateParenthesis(n - 1)){ - temp.add("(" + s + ")"); - temp.add("()" + s); - temp.add(s + "()"); - } - - for(int i = 2; i < n - 1 ; i++){ - for(String s : generateParenthesis(n - i)){ - for(String ss : generateParenthesis(i)){ - - temp.add(ss + s); - temp.add(s + ss); - } - - } - } - - return new ArrayList(temp); - } -} +public class Solution { + public List generateParenthesis(int n) { + + if (n == 0) return new ArrayList(); + if (n == 1) return Arrays.asList(new String[]{"()"}); + + HashSet temp = new HashSet(); + + for(String s : generateParenthesis(n - 1)){ + temp.add("(" + s + ")"); + temp.add("()" + s); + temp.add(s + "()"); + } + + for(int i = 2; i < n - 1 ; i++){ + for(String s : generateParenthesis(n - i)){ + for(String ss : generateParenthesis(i)){ + + temp.add(ss + s); + temp.add(s + ss); + } + + } + } + + return new ArrayList(temp); + } +} diff --git a/_includes/_root/gray-code/Solution.java b/_includes/_root/gray-code/Solution.java index e20e672..f8f383d 100644 --- a/_includes/_root/gray-code/Solution.java +++ b/_includes/_root/gray-code/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public ArrayList grayCode(int n) { - - ArrayList rt = new ArrayList(); - - - for(int i = 0; i < Math.pow(2, n); i++){ - // G(N) = (B(n)/2) XOR B(n) - rt.add((i / 2) ^ i); - } - - return rt; - - } +public class Solution { + public ArrayList grayCode(int n) { + + ArrayList rt = new ArrayList(); + + + for(int i = 0; i < Math.pow(2, n); i++){ + // G(N) = (B(n)/2) XOR B(n) + rt.add((i / 2) ^ i); + } + + return rt; + + } } \ No newline at end of file diff --git a/_includes/_root/implement-strstr/Solution.java b/_includes/_root/implement-strstr/Solution.java index 617bbeb..b606da4 100644 --- a/_includes/_root/implement-strstr/Solution.java +++ b/_includes/_root/implement-strstr/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - public String strStr(String haystack, String needle) { - - if(haystack == null) return null; - if(needle == null) return null; - - char[] _haystack = haystack.toCharArray(); - char[] _needle = needle.toCharArray(); - - if(_needle.length == 0) return haystack; - if(_haystack.length < _needle.length) return null; - - - int[] P = new int[_needle.length]; - - for(int j = 2; j < _needle.length; j++){ - - int k = 0; - - if(_needle[0 + P[j - 1]] == _needle[j - 1]){ - k = P[j - 1] + 1; - } - - P[j] = k; - } - - next: - for(int i = 0; i < _haystack.length; /*void*/){ - - for(int j = 0; j < _needle.length; j++){ - - if(i + j >= _haystack.length) return null; - - if(_haystack[i + j] != _needle[j]){ - i += Math.max(1, j - P[j]); - continue next; - } - } - - return new String(_haystack, i, _haystack.length - i); - } - - return null; - } +public class Solution { + public String strStr(String haystack, String needle) { + + if(haystack == null) return null; + if(needle == null) return null; + + char[] _haystack = haystack.toCharArray(); + char[] _needle = needle.toCharArray(); + + if(_needle.length == 0) return haystack; + if(_haystack.length < _needle.length) return null; + + + int[] P = new int[_needle.length]; + + for(int j = 2; j < _needle.length; j++){ + + int k = 0; + + if(_needle[0 + P[j - 1]] == _needle[j - 1]){ + k = P[j - 1] + 1; + } + + P[j] = k; + } + + next: + for(int i = 0; i < _haystack.length; /*void*/){ + + for(int j = 0; j < _needle.length; j++){ + + if(i + j >= _haystack.length) return null; + + if(_haystack[i + j] != _needle[j]){ + i += Math.max(1, j - P[j]); + continue next; + } + } + + return new String(_haystack, i, _haystack.length - i); + } + + return null; + } } \ No newline at end of file diff --git a/_includes/_root/insert-interval/Solution.java b/_includes/_root/insert-interval/Solution.java index 242ddf0..f63b911 100644 --- a/_includes/_root/insert-interval/Solution.java +++ b/_includes/_root/insert-interval/Solution.java @@ -1,45 +1,45 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List insert(List intervals, Interval newInterval) { - - int pos = intervals.size(); - - for(int i = 0; i < intervals.size(); i++){ - if(newInterval.start <= intervals.get(i).start){ - pos = i; - break; - } - } - - intervals.add(pos, newInterval); - - - ArrayList rt = new ArrayList(); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + public List insert(List intervals, Interval newInterval) { + + int pos = intervals.size(); + + for(int i = 0; i < intervals.size(); i++){ + if(newInterval.start <= intervals.get(i).start){ + pos = i; + break; + } + } + + intervals.add(pos, newInterval); + + + ArrayList rt = new ArrayList(); + + LinkedList s = new LinkedList(intervals); + + while (s.size() > 1) { + Interval i1 = s.pop(); + Interval i2 = s.pop(); + + if (i1.end >= i2.start) { + s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); + } else { + s.push(i2); + rt.add(i1); + } + } + + rt.addAll(s); + + return rt; + } +} diff --git a/_includes/_root/insertion-sort-list/Solution.java b/_includes/_root/insertion-sort-list/Solution.java index 82cd1be..f604a9b 100644 --- a/_includes/_root/insertion-sort-list/Solution.java +++ b/_includes/_root/insertion-sort-list/Solution.java @@ -1,59 +1,59 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode insertionSortList(ListNode head) { - - if(head == null) return null; - if(head.next == null) return head; - - final ListNode _head = new ListNode(Integer.MIN_VALUE); - _head.next = head; - - head = head.next; - _head.next.next = null; - - next: - while(head != null){ - - ListNode taken = head; - head = head.next; - - - ListNode cur = _head.next; - ListNode last = _head; - - - while(cur != null){ - - if(cur.val > taken.val){ - // insert - last.next = taken; - taken.next = cur; - - continue next; - - } - - cur = cur.next; - last = last.next; - } - - last.next = taken; - taken.next = null; - - } - - - return _head.next; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode insertionSortList(ListNode head) { + + if(head == null) return null; + if(head.next == null) return head; + + final ListNode _head = new ListNode(Integer.MIN_VALUE); + _head.next = head; + + head = head.next; + _head.next.next = null; + + next: + while(head != null){ + + ListNode taken = head; + head = head.next; + + + ListNode cur = _head.next; + ListNode last = _head; + + + while(cur != null){ + + if(cur.val > taken.val){ + // insert + last.next = taken; + taken.next = cur; + + continue next; + + } + + cur = cur.next; + last = last.next; + } + + last.next = taken; + taken.next = null; + + } + + + return _head.next; + + } } \ No newline at end of file diff --git a/_includes/_root/integer-to-roman/Solution.java b/_includes/_root/integer-to-roman/Solution.java index 341bfc5..58dc6c6 100644 --- a/_includes/_root/integer-to-roman/Solution.java +++ b/_includes/_root/integer-to-roman/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - public String intToRoman(int num) { - - String buff = ""; - char last = 0; - int samecount = 0; - - while (num > 0){ - for(int i = N.length - 1; i >= 0; i--){ - if(num >= N[i]){ - num -= N[i]; - buff += C[i]; - - if(last == C[i]){ - samecount++; - }else{ - samecount = 0; - } - - - if(samecount == 3){ - int s = 5 * N[i]; - - buff = buff.substring(0, buff.length() - 4); - - if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){ - s += N[i + 1]; - buff = buff.substring(0, buff.length() - 1); - } - - - return buff + C[i] + intToRoman(s) + intToRoman(num); - } - - last = C[i]; - break; - } - } - } - - return buff; - - } +public class Solution { + + /* + http://en.wikipedia.org/wiki/Roman_numerals + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1,000 + + to avoid four characters being repeated in succession + */ + + static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; + static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; + + public String intToRoman(int num) { + + String buff = ""; + char last = 0; + int samecount = 0; + + while (num > 0){ + for(int i = N.length - 1; i >= 0; i--){ + if(num >= N[i]){ + num -= N[i]; + buff += C[i]; + + if(last == C[i]){ + samecount++; + }else{ + samecount = 0; + } + + + if(samecount == 3){ + int s = 5 * N[i]; + + buff = buff.substring(0, buff.length() - 4); + + if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){ + s += N[i + 1]; + buff = buff.substring(0, buff.length() - 1); + } + + + return buff + C[i] + intToRoman(s) + intToRoman(num); + } + + last = C[i]; + break; + } + } + } + + return buff; + + } } \ No newline at end of file diff --git a/_includes/_root/interleaving-string/Solution.java b/_includes/_root/interleaving-string/Solution.java index bf7bcbf..1208d2e 100644 --- a/_includes/_root/interleaving-string/Solution.java +++ b/_includes/_root/interleaving-string/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - - char[] S1 = s1.toCharArray(); - char[] S2 = s2.toCharArray(); - char[] S3 = s3.toCharArray(); - - if(S1.length + S2.length != S3.length) return false; - - int i; - int j; - - boolean[][] map = new boolean[S1.length + 1][S2.length + 1]; - // i -> s1, j -> s2 - - map[0][0] = true; - - for(i = 1; i <= S1.length; i++){ - map[i][0] = map[i - 1][0] && S1[i - 1] == S3[i - 1]; - } - - for(j = 1; j <= S2.length; j++){ - map[0][j] = map[0][j - 1] && S2[j - 1] == S3[j - 1]; - } - - for(i = 1; i <= S1.length; i++){ - for(j = 1; j <= S2.length; j++){ - - if(map[i - 1][j]){ - map[i][j] = S3[i + j - 1] == S1[i - 1]; - continue; - } - - if(map[i][j - 1]){ - map[i][j] = S3[i + j - 1] == S2[j - 1]; - continue; - } - - } - } - - return map[S1.length][S2.length]; - - } +public class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + + char[] S1 = s1.toCharArray(); + char[] S2 = s2.toCharArray(); + char[] S3 = s3.toCharArray(); + + if(S1.length + S2.length != S3.length) return false; + + int i; + int j; + + boolean[][] map = new boolean[S1.length + 1][S2.length + 1]; + // i -> s1, j -> s2 + + map[0][0] = true; + + for(i = 1; i <= S1.length; i++){ + map[i][0] = map[i - 1][0] && S1[i - 1] == S3[i - 1]; + } + + for(j = 1; j <= S2.length; j++){ + map[0][j] = map[0][j - 1] && S2[j - 1] == S3[j - 1]; + } + + for(i = 1; i <= S1.length; i++){ + for(j = 1; j <= S2.length; j++){ + + if(map[i - 1][j]){ + map[i][j] = S3[i + j - 1] == S1[i - 1]; + continue; + } + + if(map[i][j - 1]){ + map[i][j] = S3[i + j - 1] == S2[j - 1]; + continue; + } + + } + } + + return map[S1.length][S2.length]; + + } } \ No newline at end of file diff --git a/_includes/_root/intersection-of-two-linked-lists/README.md b/_includes/_root/intersection-of-two-linked-lists/README.md index 3cd5882..f5548cb 100644 --- a/_includes/_root/intersection-of-two-linked-lists/README.md +++ b/_includes/_root/intersection-of-two-linked-lists/README.md @@ -1,22 +1,22 @@ -## Two Lists with same length - - -``` - -A: a1 → a2 - ↘ - c1 → c2 → c3 - ↗ -B: b1 → b2 - - -``` - -Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. - -## What if the length is not the same - -Make them the same. - - * find out two lists' length - * trim the longer one and remove the `overhead` +## Two Lists with same length + + +``` + +A: a1 → a2 + ↘ + c1 → c2 → c3 + ↗ +B: b1 → b2 + + +``` + +Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. + +## What if the length is not the same + +Make them the same. + + * find out two lists' length + * trim the longer one and remove the `overhead` diff --git a/_includes/_root/jump-game-ii/Solution.java b/_includes/_root/jump-game-ii/Solution.java index cf6d45f..19b1101 100644 --- a/_includes/_root/jump-game-ii/Solution.java +++ b/_includes/_root/jump-game-ii/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int jump(int[] A) { - int count = 0; - int laststep = 0; - - for(int i = 0; i < A.length - 1; /**/){ - - int maxstep = i + A[i]; - for(int j = laststep + 1; j <= i; j++){ - maxstep = Math.max(maxstep, j + A[j]); - } - - laststep = i; - i = maxstep; - - count++; - } - - return count; - } +public class Solution { + public int jump(int[] A) { + int count = 0; + int laststep = 0; + + for(int i = 0; i < A.length - 1; /**/){ + + int maxstep = i + A[i]; + for(int j = laststep + 1; j <= i; j++){ + maxstep = Math.max(maxstep, j + A[j]); + } + + laststep = i; + i = maxstep; + + count++; + } + + return count; + } } \ No newline at end of file diff --git a/_includes/_root/jump-game/Solution.java b/_includes/_root/jump-game/Solution.java index a409a8e..6ed7274 100644 --- a/_includes/_root/jump-game/Solution.java +++ b/_includes/_root/jump-game/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - - - - public boolean canJump(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(A.length == 0) return false; - - - int maxjump = 0; - - for(int i = 0; i < A.length; i++){ - if(i <= maxjump){ - if(i + A[i] < A.length - 1){ - maxjump = Math.max(maxjump, i + A[i]); - }else{ - return true; - } - } else { - return false; - } - } - - return false; - } +public class Solution { + + + + public boolean canJump(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(A.length == 0) return false; + + + int maxjump = 0; + + for(int i = 0; i < A.length; i++){ + if(i <= maxjump){ + if(i + A[i] < A.length - 1){ + maxjump = Math.max(maxjump, i + A[i]); + }else{ + return true; + } + } else { + return false; + } + } + + return false; + } } \ No newline at end of file diff --git a/_includes/_root/largest-rectangle-in-histogram/Solution.java b/_includes/_root/largest-rectangle-in-histogram/Solution.java index eb9dc93..4228568 100644 --- a/_includes/_root/largest-rectangle-in-histogram/Solution.java +++ b/_includes/_root/largest-rectangle-in-histogram/Solution.java @@ -1,52 +1,52 @@ -public class Solution { - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } +public class Solution { + + static class Rect { + int width = 1; + int height; + + Rect(int height){ + this.height = height; + } + } + + public int largestRectangleArea(int[] height) { + + if(height.length == 0) return 0; + + height = Arrays.copyOf(height, height.length + 1); + height[height.length - 1] = 0; + + Deque stack = new LinkedList(); + + stack.push(new Rect(height[0])); + + int max = 0; + + next: + for(int i = 1; i < height.length; i++){ + int h = height[i]; + + Rect r = new Rect(h); + + int sl = 0; + while(true){ + + if(stack.isEmpty() || h > stack.peek().height){ + stack.push(r); + continue next; + } + + + Rect left = stack.pop(); + + sl += left.width; + max = Math.max(max, left.height * sl); + + r.width = 1 + sl ; // merge left into new + } + + } + + return max; + } } \ No newline at end of file diff --git a/_includes/_root/length-of-last-word/Solution.java b/_includes/_root/length-of-last-word/Solution.java index e82e9e6..af1a9b9 100644 --- a/_includes/_root/length-of-last-word/Solution.java +++ b/_includes/_root/length-of-last-word/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int lengthOfLastWord(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s == null) return 0; - - char[] chars = s.toCharArray(); - - int upper = chars.length - 1; - while(upper >=0 && chars[upper] == ' ') upper--; - - int len = 0; - for(int i = 0; i<= upper; i++){ - if(chars[i] == ' ')len = 0; - else len++; - } - - return len; - - } +public class Solution { + public int lengthOfLastWord(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(s == null) return 0; + + char[] chars = s.toCharArray(); + + int upper = chars.length - 1; + while(upper >=0 && chars[upper] == ' ') upper--; + + int len = 0; + for(int i = 0; i<= upper; i++){ + if(chars[i] == ' ')len = 0; + else len++; + } + + return len; + + } } \ No newline at end of file diff --git a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java b/_includes/_root/letter-combinations-of-a-phone-number/Solution.java index 6760c44..b5c047b 100644 --- a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java +++ b/_includes/_root/letter-combinations-of-a-phone-number/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - static final char[][] CHAR_MAP = { - null, // 0 - null, // 1 - new char[] { 'a', 'b', 'c'}, //2 - new char[] { 'd', 'e', 'f'}, //3 - new char[] { 'g', 'h', 'i'}, //4 - new char[] { 'j', 'k', 'l'}, //5 - new char[] { 'm', 'n', 'o'}, //6 - new char[] { 'p', 'q', 'r', 's'}, //7 - new char[] { 't', 'u', 'v'}, //8 - new char[] { 'w', 'x', 'y', 'z'}, //9 - }; - - ArrayList rt; - char[] stack; - - void find(char[] digits, int p){ - - if(p == digits.length){ - rt.add(new String(stack)); - }else{ - - int num = (int) (digits[p] - '0'); - - if(CHAR_MAP[num] != null) - for(char pc : CHAR_MAP[num]){ - stack[p] = pc; - find(digits, p + 1); - } - } - - } - - public ArrayList letterCombinations(String digits) { - - rt = new ArrayList(); - stack = new char[digits.length()]; - - find(digits.toCharArray(), 0); - - return rt; - } +public class Solution { + + static final char[][] CHAR_MAP = { + null, // 0 + null, // 1 + new char[] { 'a', 'b', 'c'}, //2 + new char[] { 'd', 'e', 'f'}, //3 + new char[] { 'g', 'h', 'i'}, //4 + new char[] { 'j', 'k', 'l'}, //5 + new char[] { 'm', 'n', 'o'}, //6 + new char[] { 'p', 'q', 'r', 's'}, //7 + new char[] { 't', 'u', 'v'}, //8 + new char[] { 'w', 'x', 'y', 'z'}, //9 + }; + + ArrayList rt; + char[] stack; + + void find(char[] digits, int p){ + + if(p == digits.length){ + rt.add(new String(stack)); + }else{ + + int num = (int) (digits[p] - '0'); + + if(CHAR_MAP[num] != null) + for(char pc : CHAR_MAP[num]){ + stack[p] = pc; + find(digits, p + 1); + } + } + + } + + public ArrayList letterCombinations(String digits) { + + rt = new ArrayList(); + stack = new char[digits.length()]; + + find(digits.toCharArray(), 0); + + return rt; + } } \ No newline at end of file diff --git a/_includes/_root/linked-list-cycle-ii/Solution.java b/_includes/_root/linked-list-cycle-ii/Solution.java index 892bb25..bc2e4fd 100644 --- a/_includes/_root/linked-list-cycle-ii/Solution.java +++ b/_includes/_root/linked-list-cycle-ii/Solution.java @@ -1,70 +1,70 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode detectCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - - boolean meet = false; - - int lenc = 0; - - while ( slow.next != null){ - - slow = slow.next; - - if(slow == null) return null; - - if(fast.next == null) return null; - - fast = fast.next.next; - - if(fast == null) return null; - - if(slow == fast) { - - if(meet) break; - - meet = true; - } - - if(meet){ - lenc++; - } - } - - if(meet){ - - slow = head; - fast = head; - for(int i = 0; i< lenc; i++){ - fast = fast.next; - } - - while(slow != fast){ - slow = slow.next; - fast = fast.next; - } - - - return slow; - - } - - return null; - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + ListNode fast = head; + ListNode slow = head; + + boolean meet = false; + + int lenc = 0; + + while ( slow.next != null){ + + slow = slow.next; + + if(slow == null) return null; + + if(fast.next == null) return null; + + fast = fast.next.next; + + if(fast == null) return null; + + if(slow == fast) { + + if(meet) break; + + meet = true; + } + + if(meet){ + lenc++; + } + } + + if(meet){ + + slow = head; + fast = head; + for(int i = 0; i< lenc; i++){ + fast = fast.next; + } + + while(slow != fast){ + slow = slow.next; + fast = fast.next; + } + + + return slow; + + } + + return null; + } } \ No newline at end of file diff --git a/_includes/_root/linked-list-cycle/Solution.java b/_includes/_root/linked-list-cycle/Solution.java index 1d588e1..c40f172 100644 --- a/_includes/_root/linked-list-cycle/Solution.java +++ b/_includes/_root/linked-list-cycle/Solution.java @@ -1,37 +1,37 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public boolean hasCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return false; - - ListNode fast = head; - ListNode slow = head; - - - while(slow.next != null){ - - if(fast.next == null) return false; - - fast = fast.next.next; - - if(fast == null) return false; - - slow = slow.next; - - if(fast == slow) return true; - } - - return false; - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return false; + + ListNode fast = head; + ListNode slow = head; + + + while(slow.next != null){ + + if(fast.next == null) return false; + + fast = fast.next.next; + + if(fast == null) return false; + + slow = slow.next; + + if(fast == slow) return true; + } + + return false; + } } \ No newline at end of file diff --git a/_includes/_root/longest-common-prefix/Solution.java b/_includes/_root/longest-common-prefix/Solution.java index 9765ad9..e4af631 100644 --- a/_includes/_root/longest-common-prefix/Solution.java +++ b/_includes/_root/longest-common-prefix/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public String longestCommonPrefix(String[] strs) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int p = 0; - - if(strs.length == 0) return ""; - if(strs.length == 1) return strs[0]; - - - here: - - while(true){ - - if( p >= strs[0].length() ) break; - - char c = strs[0].charAt(p); - - for(String str : strs){ - if(str.length() <= p || str.charAt(p) != c) break here; - } - - p++; - - } - - return strs[0].substring(0, p); - - - - } +public class Solution { + public String longestCommonPrefix(String[] strs) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + int p = 0; + + if(strs.length == 0) return ""; + if(strs.length == 1) return strs[0]; + + + here: + + while(true){ + + if( p >= strs[0].length() ) break; + + char c = strs[0].charAt(p); + + for(String str : strs){ + if(str.length() <= p || str.charAt(p) != c) break here; + } + + p++; + + } + + return strs[0].substring(0, p); + + + + } } \ No newline at end of file diff --git a/_includes/_root/longest-consecutive-sequence/Solution.java b/_includes/_root/longest-consecutive-sequence/Solution.java index a703801..98fc2d9 100644 --- a/_includes/_root/longest-consecutive-sequence/Solution.java +++ b/_includes/_root/longest-consecutive-sequence/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public int longestConsecutive(int[] num) { - - HashSet nums = new HashSet(); - - for(int n : num){ - nums.add(n); - } - - int longest = 0; - - for(final int n : num){ - - int l = 1; - - int nn = n; - - nums.remove(n); - - while(nums.contains(++nn)){ - l++; - nums.remove(nn); - } - - nn = n; - - while(nums.contains(--nn)){ - l++; - nums.remove(nn); - } - - longest = Math.max(longest, l); - } - - return longest; - - } +public class Solution { + public int longestConsecutive(int[] num) { + + HashSet nums = new HashSet(); + + for(int n : num){ + nums.add(n); + } + + int longest = 0; + + for(final int n : num){ + + int l = 1; + + int nn = n; + + nums.remove(n); + + while(nums.contains(++nn)){ + l++; + nums.remove(nn); + } + + nn = n; + + while(nums.contains(--nn)){ + l++; + nums.remove(nn); + } + + longest = Math.max(longest, l); + } + + return longest; + + } } \ No newline at end of file diff --git a/_includes/_root/longest-palindromic-substring/Solution.java b/_includes/_root/longest-palindromic-substring/Solution.java index 851f8c3..6184350 100644 --- a/_includes/_root/longest-palindromic-substring/Solution.java +++ b/_includes/_root/longest-palindromic-substring/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public String longestPalindrome(String s) { - - char[] S = s.toCharArray(); - - if(S.length == 0) return ""; - - boolean[][] P = new boolean[S.length][S.length]; - - int maxi = 0; - int maxlen = 1; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - if(S[i] == S[i + 2 - 1]){ - P[2 - 1][i] = true; - maxi = i; - maxlen = 2; - } - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - - if(P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]){ - P[len - 1][i] = true; - maxi = i; - maxlen = len; - } - } - } - - return s.substring(maxi, maxi + maxlen); - } -} +public class Solution { + public String longestPalindrome(String s) { + + char[] S = s.toCharArray(); + + if(S.length == 0) return ""; + + boolean[][] P = new boolean[S.length][S.length]; + + int maxi = 0; + int maxlen = 1; + + // len 1 + Arrays.fill(P[1 - 1], true); + + // len 2 + for(int i = 0; i < S.length - 1; i++){ + if(S[i] == S[i + 2 - 1]){ + P[2 - 1][i] = true; + maxi = i; + maxlen = 2; + } + } + + // len 3 to max + for(int len = 3; len <= S.length; len++){ + + for(int i = 0; i < S.length - (len - 1); i++){ + + if(P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]){ + P[len - 1][i] = true; + maxi = i; + maxlen = len; + } + } + } + + return s.substring(maxi, maxi + maxlen); + } +} diff --git a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md index 7f82848..0c5f96c 100644 --- a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md +++ b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md @@ -1,36 +1,36 @@ -## Relative of [Minimum Window Substring](../minimum-window-substring) - -This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). - -## Loop invariant - -Assume that `S` is a `string with at most two distinct char` - -when a new char `c` comes: - * append it to `S`'s right - * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` - -``` -S = 'aabb' - -new char c = 'c' - -S = 'aabbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'abbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'bbc' - -``` - - -## Finding max - -after each loop, `S` is a `string with at most two distinct char`. but, its length changes. -what we need is to find the max length. +## Relative of [Minimum Window Substring](../minimum-window-substring) + +This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). + +## Loop invariant + +Assume that `S` is a `string with at most two distinct char` + +when a new char `c` comes: + * append it to `S`'s right + * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` + +``` +S = 'aabb' + +new char c = 'c' + +S = 'aabbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'abbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'bbc' + +``` + + +## Finding max + +after each loop, `S` is a `string with at most two distinct char`. but, its length changes. +what we need is to find the max length. diff --git a/_includes/_root/longest-substring-without-repeating-characters/Solution.java b/_includes/_root/longest-substring-without-repeating-characters/Solution.java index 0e6b9ae..10a18fd 100644 --- a/_includes/_root/longest-substring-without-repeating-characters/Solution.java +++ b/_includes/_root/longest-substring-without-repeating-characters/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public int lengthOfLongestSubstring(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(s == null) return 0; - char[] str = s.toCharArray(); - if(str.length == 0) return 0; - - - int max = 1; - - int barrier = 0; - - for(int i = 1; i < str.length; i++){ - for(int j = i - 1; j >= barrier;j--){ - if(str[i] == str[j]){ - barrier = j + 1; - break; - } - } - - max = Math.max(max, i - barrier + 1); - } - - - return max; - - } +public class Solution { + public int lengthOfLongestSubstring(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(s == null) return 0; + char[] str = s.toCharArray(); + if(str.length == 0) return 0; + + + int max = 1; + + int barrier = 0; + + for(int i = 1; i < str.length; i++){ + for(int j = i - 1; j >= barrier;j--){ + if(str[i] == str[j]){ + barrier = j + 1; + break; + } + } + + max = Math.max(max, i - barrier + 1); + } + + + return max; + + } } \ No newline at end of file diff --git a/_includes/_root/longest-valid-parentheses/Solution.java b/_includes/_root/longest-valid-parentheses/Solution.java index fdb64f3..744f00d 100644 --- a/_includes/_root/longest-valid-parentheses/Solution.java +++ b/_includes/_root/longest-valid-parentheses/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public int longestValidParentheses(String s) { - if(s == null) return 0; - - char[] chars = s.toCharArray(); - if(chars.length <= 1) return 0; - - LinkedList stack = new LinkedList(); - - int[] count = new int[chars.length]; - int max = 0; - - for(int i = 0 ; i stack = new LinkedList(); + + int[] count = new int[chars.length]; + int max = 0; + + for(int i = 0 ; i= capacity){ - removeOneFromTail(); - size--; - } - - e = new Entry(); - - e.key = key; - e.value = value; - - addBeforeHead(e); - - int h = hash(e.key); - Entry d = data[h]; - - if(d == null){ - data[h] = e; - } else { - while(d.hashnext != null){ - d = d.hashnext; - } - - d.hashnext = e; - } - - size++; - - } +public class LRUCache { + + static class Entry { + int key; + int value; + + Entry hashnext; + + Entry linknext; + Entry linkprev; + } + + Entry[] data; + + int capacity; + int size; + + Entry head; + Entry tail; + + public LRUCache(int capacity) { + this.capacity = capacity; + data = new Entry[capacity + capacity/2 + 3]; + size = 0; + + head = new Entry(); + tail = new Entry(); + + head.linknext = tail; + tail.linkprev = head; + } + + int hash(int key){ + return key % capacity; + } + + void moveToHead(Entry e){ + + Entry before = e.linkprev; + Entry after = e.linknext; + + before.linknext = after; + after.linkprev = before; + + addBeforeHead(e); + } + + void addBeforeHead(Entry e){ + Entry chead = head.linknext; + chead.linkprev = e; + head.linknext = e; + + e.linkprev = head; + e.linknext = chead; + } + + Entry _get(int key){ + int h = hash(key); + Entry e = data[h]; + + while(e != null){ + if(e.key == key){ + moveToHead(e); + return e; + } + + e = e.hashnext; + } + + return null; + } + + public int get(int key) { + Entry e = _get(key); + + if(e == null){ + return -1; + } + + return e.value; + } + + void removeOneFromTail(){ + Entry e = tail.linkprev; + + tail.linkprev = e.linkprev; + tail.linkprev.linknext = tail; + + int h = hash(e.key); + + Entry d = data[h]; + + if(d == e || d.key == e.key){ + data[h] = e.hashnext; + return; + } + + Entry p = d; + d = d.hashnext; + + while(d != null){ + + if(d == e){ + p.hashnext = e.hashnext; + return; + } + p = d; + d = d.hashnext; + } + + } + + public void set(int key, int value) { + if(capacity == 0) return; + + Entry e = _get(key); + if(e != null){ + e.value = value; + return; + } + + if(size >= capacity){ + removeOneFromTail(); + size--; + } + + e = new Entry(); + + e.key = key; + e.value = value; + + addBeforeHead(e); + + int h = hash(e.key); + Entry d = data[h]; + + if(d == null){ + data[h] = e; + } else { + while(d.hashnext != null){ + d = d.hashnext; + } + + d.hashnext = e; + } + + size++; + + } } \ No newline at end of file diff --git a/_includes/_root/max-points-on-a-line/Solution.java b/_includes/_root/max-points-on-a-line/Solution.java index 8866bac..9a990e2 100644 --- a/_includes/_root/max-points-on-a-line/Solution.java +++ b/_includes/_root/max-points-on-a-line/Solution.java @@ -1,78 +1,78 @@ -/** - * Definition for a point. - * class Point { - * int x; - * int y; - * Point() { x = 0; y = 0; } - * Point(int a, int b) { x = a; y = b; } - * } - */ -public class Solution { - - static class Line{ - - Point p1; - Point p2; - - int pointCount; - - Line(Point p1, Point p2){ - this.p1 = p1; - this.p2 = p2; - - this.pointCount = 2; - } - - boolean on(int x, int y){ - return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x); - } - - boolean on(Point p){ - return on(p.x, p.y); - } - } - - public int maxPoints(Point[] points) { - - if(points.length < 2) return points.length; - - ArrayList lines = new ArrayList(); - - lines.add(new Line(points[0], points[1])); - - for(int i = 2; i < points.length; i++){ - boolean on = false; - for(Line line : lines){ - if(line.on(points[i])){ - line.pointCount++; - on = true; - } - } - - if(!on){ - for(int j = 0; j < i; j++){ - Line l = new Line(points[j], points[i]); - lines.add(l); - - for(int k = 0; k < i; k++){ - if(j != k && l.on(points[k])){ - l.pointCount++; - break; - } - - } - } - } - } - - - int max = Integer.MIN_VALUE; - - for(Line line : lines){ - if(line.pointCount > max) max = line.pointCount; - } - - return max; - - } +/** + * Definition for a point. + * class Point { + * int x; + * int y; + * Point() { x = 0; y = 0; } + * Point(int a, int b) { x = a; y = b; } + * } + */ +public class Solution { + + static class Line{ + + Point p1; + Point p2; + + int pointCount; + + Line(Point p1, Point p2){ + this.p1 = p1; + this.p2 = p2; + + this.pointCount = 2; + } + + boolean on(int x, int y){ + return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x); + } + + boolean on(Point p){ + return on(p.x, p.y); + } + } + + public int maxPoints(Point[] points) { + + if(points.length < 2) return points.length; + + ArrayList lines = new ArrayList(); + + lines.add(new Line(points[0], points[1])); + + for(int i = 2; i < points.length; i++){ + boolean on = false; + for(Line line : lines){ + if(line.on(points[i])){ + line.pointCount++; + on = true; + } + } + + if(!on){ + for(int j = 0; j < i; j++){ + Line l = new Line(points[j], points[i]); + lines.add(l); + + for(int k = 0; k < i; k++){ + if(j != k && l.on(points[k])){ + l.pointCount++; + break; + } + + } + } + } + } + + + int max = Integer.MIN_VALUE; + + for(Line line : lines){ + if(line.pointCount > max) max = line.pointCount; + } + + return max; + + } } \ No newline at end of file diff --git a/_includes/_root/maximal-rectangle/Solution.java b/_includes/_root/maximal-rectangle/Solution.java index 56aee75..68873f4 100644 --- a/_includes/_root/maximal-rectangle/Solution.java +++ b/_includes/_root/maximal-rectangle/Solution.java @@ -1,116 +1,116 @@ -public class Solution { - public int maximalRectangle(char[][] matrix) { - int x; - int y; - - int mx = matrix.length; - if(mx == 0) return 0; - int my = matrix[0].length; - if(my == 0) return 0; - - - int[][] _matrix = new int[mx][my]; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - - int max = 0; - - for (x = 0; x < mx; x++){ - for(y = my - 1; y > 0; y--){ - if(matrix[x][y - 1] != '0' && matrix[x][y] != '0'){ - _matrix[x][y - 1] += _matrix[x][y]; - } - } - } - - for(y = 0; y < my; y++){ - - int h[] = new int[mx]; - - for(x = 0; x < mx; x++) - h[x] = _matrix[x][y]; - - max = Math.max(max, largestRectangleArea(h)); - } - - _matrix = new int[mx][my]; - - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - for (y = 0; y < my; y++){ - for(x = mx - 1; x > 0; x--){ - if(matrix[x - 1][y] != '0' && matrix[x][y] != '0'){ - _matrix[x - 1][y] += _matrix[x][y]; - } - } - } - - for(x = 0; x < mx; x++){ - max = Math.max(max, largestRectangleArea(_matrix[x])); - } - - - return max; - } - - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } +public class Solution { + public int maximalRectangle(char[][] matrix) { + int x; + int y; + + int mx = matrix.length; + if(mx == 0) return 0; + int my = matrix[0].length; + if(my == 0) return 0; + + + int[][] _matrix = new int[mx][my]; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++) { + _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; + } + } + + + int max = 0; + + for (x = 0; x < mx; x++){ + for(y = my - 1; y > 0; y--){ + if(matrix[x][y - 1] != '0' && matrix[x][y] != '0'){ + _matrix[x][y - 1] += _matrix[x][y]; + } + } + } + + for(y = 0; y < my; y++){ + + int h[] = new int[mx]; + + for(x = 0; x < mx; x++) + h[x] = _matrix[x][y]; + + max = Math.max(max, largestRectangleArea(h)); + } + + _matrix = new int[mx][my]; + + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++) { + _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; + } + } + + for (y = 0; y < my; y++){ + for(x = mx - 1; x > 0; x--){ + if(matrix[x - 1][y] != '0' && matrix[x][y] != '0'){ + _matrix[x - 1][y] += _matrix[x][y]; + } + } + } + + for(x = 0; x < mx; x++){ + max = Math.max(max, largestRectangleArea(_matrix[x])); + } + + + return max; + } + + + static class Rect { + int width = 1; + int height; + + Rect(int height){ + this.height = height; + } + } + + public int largestRectangleArea(int[] height) { + + if(height.length == 0) return 0; + + height = Arrays.copyOf(height, height.length + 1); + height[height.length - 1] = 0; + + Deque stack = new LinkedList(); + + stack.push(new Rect(height[0])); + + int max = 0; + + next: + for(int i = 1; i < height.length; i++){ + int h = height[i]; + + Rect r = new Rect(h); + + int sl = 0; + while(true){ + + if(stack.isEmpty() || h > stack.peek().height){ + stack.push(r); + continue next; + } + + + Rect left = stack.pop(); + + sl += left.width; + max = Math.max(max, left.height * sl); + + r.width = 1 + sl ; // merge left into new + } + + } + + return max; + } } \ No newline at end of file diff --git a/_includes/_root/maximum-depth-of-binary-tree/Solution.java b/_includes/_root/maximum-depth-of-binary-tree/Solution.java index db6e596..df368fd 100644 --- a/_includes/_root/maximum-depth-of-binary-tree/Solution.java +++ b/_includes/_root/maximum-depth-of-binary-tree/Solution.java @@ -1,17 +1,17 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int maxDepth(TreeNode root) { - - if(root == null) return 0; - - return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int maxDepth(TreeNode root) { + + if(root == null) return 0; + + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} diff --git a/_includes/_root/maximum-gap/README.md b/_includes/_root/maximum-gap/README.md index eb7dbb2..3365673 100644 --- a/_includes/_root/maximum-gap/README.md +++ b/_includes/_root/maximum-gap/README.md @@ -1,32 +1,32 @@ -## `O(n)` Sort - -The problem requires `O(n)` time complexity, and it looks something like sort. -[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) -are the two well known `O(n)` sort. - -Maybe an `O(32n)` radix sort will work well. - -## Bucket sort version - -> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. -Through, this solution got accepted by leetcode, I found there is a better solution. - -the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, -the `maximum gap` must be greater than `(max - min) / (N - 1)`. - -Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, -but, this time a good news is that we do not need to sort the numbers in the buckets, -what we need is only to remember the max and min of the bucket. -The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. - -after bucketing, numbers are like - -``` -[MIN] [MIN] [MIN] -[ ] [ ] ... [ ] -[MAX] [MAX] [MAX] -``` - -The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. - -Note: the will be some emtpy buckets, skip them. +## `O(n)` Sort + +The problem requires `O(n)` time complexity, and it looks something like sort. +[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) +are the two well known `O(n)` sort. + +Maybe an `O(32n)` radix sort will work well. + +## Bucket sort version + +> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. +Through, this solution got accepted by leetcode, I found there is a better solution. + +the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, +the `maximum gap` must be greater than `(max - min) / (N - 1)`. + +Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, +but, this time a good news is that we do not need to sort the numbers in the buckets, +what we need is only to remember the max and min of the bucket. +The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. + +after bucketing, numbers are like + +``` +[MIN] [MIN] [MIN] +[ ] [ ] ... [ ] +[MAX] [MAX] [MAX] +``` + +The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. + +Note: the will be some emtpy buckets, skip them. diff --git a/_includes/_root/maximum-subarray/Solution.java b/_includes/_root/maximum-subarray/Solution.java index 2e0fb5d..ede5dd2 100644 --- a/_includes/_root/maximum-subarray/Solution.java +++ b/_includes/_root/maximum-subarray/Solution.java @@ -1,20 +1,20 @@ -public class Solution { - public int maxSubArray(int[] A) { - - int max = A[0]; - int history = A[0]; - - for(int i = 1; i < A.length; i++){ - if(history < 0){ - history = A[i]; - }else{ - history += A[i]; - } - - max = Math.max(max, history); - - } - - return max; - } -} +public class Solution { + public int maxSubArray(int[] A) { + + int max = A[0]; + int history = A[0]; + + for(int i = 1; i < A.length; i++){ + if(history < 0){ + history = A[i]; + }else{ + history += A[i]; + } + + max = Math.max(max, history); + + } + + return max; + } +} diff --git a/_includes/_root/median-of-two-sorted-arrays/Solution.java b/_includes/_root/median-of-two-sorted-arrays/Solution.java index 007616d..4d7a58c 100644 --- a/_includes/_root/median-of-two-sorted-arrays/Solution.java +++ b/_includes/_root/median-of-two-sorted-arrays/Solution.java @@ -1,80 +1,80 @@ -public class Solution { - - int safe(int[] X, int i){ - - if ( i < 0) return Integer.MIN_VALUE; - - if ( i >= X.length) return Integer.MAX_VALUE; - - return X[i]; - } - - int kth(int[] A, int[] B, int k){ - - if (A.length == 0) - return B[k]; - - if (B.length == 0) - return A[k]; - - if (k == 0) - return Math.min(A[0], B[0]); - - if (A.length == 1 && B.length == 1){ - // k must be 1 - return Math.max(A[0], B[0]); - } - - int s = 0; - int e = A.length; - - while ( s < e ){ - - int m = (s + e) / 2; - - int n = k - m; - - if ( A[m] <= safe(B, n) ) { - if (n == 0 || A[m] >= safe(B, n - 1)) { - return A[m]; - } - } - - if ( safe(B, n) <= A[m] ){ - if (m == 0 || safe(B, n) >= A[m - 1]) { - return B[n]; - } - } - - if ( A[m] < safe(B, n) ) { - s = m + 1; - } else { - e = m; - } - - } - - if (A[A.length - 1] < B[0]){ - return B[k - A.length]; - } else { - return kth(B, A, k); - } - - } - - - public double findMedianSortedArrays(int A[], int B[]) { - // median of {3, 3, 5, 9, 11} is 5 - // the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 wikipedia - - int s = A.length + B.length; - final int k = s / 2; - - if(s % 2 == 1){ - return kth(A, B, k); - }else{ - return (kth(A, B, k - 1) + kth(A, B, k)) / 2.0; - } - - } +public class Solution { + + int safe(int[] X, int i){ + + if ( i < 0) return Integer.MIN_VALUE; + + if ( i >= X.length) return Integer.MAX_VALUE; + + return X[i]; + } + + int kth(int[] A, int[] B, int k){ + + if (A.length == 0) + return B[k]; + + if (B.length == 0) + return A[k]; + + if (k == 0) + return Math.min(A[0], B[0]); + + if (A.length == 1 && B.length == 1){ + // k must be 1 + return Math.max(A[0], B[0]); + } + + int s = 0; + int e = A.length; + + while ( s < e ){ + + int m = (s + e) / 2; + + int n = k - m; + + if ( A[m] <= safe(B, n) ) { + if (n == 0 || A[m] >= safe(B, n - 1)) { + return A[m]; + } + } + + if ( safe(B, n) <= A[m] ){ + if (m == 0 || safe(B, n) >= A[m - 1]) { + return B[n]; + } + } + + if ( A[m] < safe(B, n) ) { + s = m + 1; + } else { + e = m; + } + + } + + if (A[A.length - 1] < B[0]){ + return B[k - A.length]; + } else { + return kth(B, A, k); + } + + } + + + public double findMedianSortedArrays(int A[], int B[]) { + // median of {3, 3, 5, 9, 11} is 5 + // the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 wikipedia + + int s = A.length + B.length; + final int k = s / 2; + + if(s % 2 == 1){ + return kth(A, B, k); + }else{ + return (kth(A, B, k - 1) + kth(A, B, k)) / 2.0; + } + + } } \ No newline at end of file diff --git a/_includes/_root/merge-intervals/Solution.java b/_includes/_root/merge-intervals/Solution.java index 3a41e09..efab953 100644 --- a/_includes/_root/merge-intervals/Solution.java +++ b/_includes/_root/merge-intervals/Solution.java @@ -1,39 +1,39 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List merge(List intervals) { - - ArrayList rt = new ArrayList(); - - Collections.sort(intervals, new Comparator() { - public int compare(Interval o1, Interval o2) { - return o1.start - o2.start; - } - }); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + public List merge(List intervals) { + + ArrayList rt = new ArrayList(); + + Collections.sort(intervals, new Comparator() { + public int compare(Interval o1, Interval o2) { + return o1.start - o2.start; + } + }); + + LinkedList s = new LinkedList(intervals); + + while (s.size() > 1) { + Interval i1 = s.pop(); + Interval i2 = s.pop(); + + if (i1.end >= i2.start) { + s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); + } else { + s.push(i2); + rt.add(i1); + } + } + + rt.addAll(s); + + return rt; + } +} diff --git a/_includes/_root/merge-k-sorted-lists/Solution.java b/_includes/_root/merge-k-sorted-lists/Solution.java index 050969d..3760de2 100644 --- a/_includes/_root/merge-k-sorted-lists/Solution.java +++ b/_includes/_root/merge-k-sorted-lists/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode mergeTwoLists(ListNode l1, ListNode l2) { - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - } - - public ListNode mergeKLists(List lists) { - - final int size = lists.size(); - - if(size == 0) return null; - if(size == 1) return lists.get(0); - if(size == 2) return mergeTwoLists(lists.get(0), lists.get(1)); - - return mergeTwoLists(mergeKLists(lists.subList(0, size / 2)), mergeKLists(lists.subList(size / 2, size))); - } -} +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + } + + public ListNode mergeKLists(List lists) { + + final int size = lists.size(); + + if(size == 0) return null; + if(size == 1) return lists.get(0); + if(size == 2) return mergeTwoLists(lists.get(0), lists.get(1)); + + return mergeTwoLists(mergeKLists(lists.subList(0, size / 2)), mergeKLists(lists.subList(size / 2, size))); + } +} diff --git a/_includes/_root/merge-sorted-array/Solution.java b/_includes/_root/merge-sorted-array/Solution.java index 2a5fa48..c937f40 100644 --- a/_includes/_root/merge-sorted-array/Solution.java +++ b/_includes/_root/merge-sorted-array/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public void merge(int A[], int m, int B[], int n) { - - int pa = 0; - int pb = 0; - int up = 0; - - while(pa < m + pb && pb < n){ - - int a = A[pa]; - int b = B[pb]; - - if (a < b){ - pa++; - }else{ - // shift up - for(int i = pb + m; i > pa ; i--){ - A[i] = A[i - 1]; - } - - A[pa] = b; - pa++; - pb++; - } - - } - - for( ; pb < n; pb++){ - A[pb + m] = B[pb]; - } - - } +public class Solution { + public void merge(int A[], int m, int B[], int n) { + + int pa = 0; + int pb = 0; + int up = 0; + + while(pa < m + pb && pb < n){ + + int a = A[pa]; + int b = B[pb]; + + if (a < b){ + pa++; + }else{ + // shift up + for(int i = pb + m; i > pa ; i--){ + A[i] = A[i - 1]; + } + + A[pa] = b; + pa++; + pb++; + } + + } + + for( ; pb < n; pb++){ + A[pb + m] = B[pb]; + } + + } } \ No newline at end of file diff --git a/_includes/_root/merge-two-sorted-lists/Solution.java b/_includes/_root/merge-two-sorted-lists/Solution.java index 37aa0bc..514d87b 100644 --- a/_includes/_root/merge-two-sorted-lists/Solution.java +++ b/_includes/_root/merge-two-sorted-lists/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + + + } } \ No newline at end of file diff --git a/_includes/_root/minimum-depth-of-binary-tree/Solution.java b/_includes/_root/minimum-depth-of-binary-tree/Solution.java index 2a97ffa..e1e9fde 100644 --- a/_includes/_root/minimum-depth-of-binary-tree/Solution.java +++ b/_includes/_root/minimum-depth-of-binary-tree/Solution.java @@ -1,22 +1,22 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int minDepth(TreeNode root) { - - if(root == null) return 0; - if(root.left == null && root.right == null) return 1; - - if(root.left != null && root.right == null) return minDepth(root.left) + 1; - if(root.left == null && root.right != null) return minDepth(root.right) + 1; - - return Math.min(minDepth(root.left), minDepth(root.right)) + 1; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int minDepth(TreeNode root) { + + if(root == null) return 0; + if(root.left == null && root.right == null) return 1; + + if(root.left != null && root.right == null) return minDepth(root.left) + 1; + if(root.left == null && root.right != null) return minDepth(root.right) + 1; + + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; + + } +} diff --git a/_includes/_root/minimum-path-sum/Solution.java b/_includes/_root/minimum-path-sum/Solution.java index e4f9e8a..129901d 100644 --- a/_includes/_root/minimum-path-sum/Solution.java +++ b/_includes/_root/minimum-path-sum/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public int minPathSum(int[][] grid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - - int mx = grid.length; - if(mx == 0) return 0; - - int my = grid[0].length; - - for(int x = 1; x < mx ; x++){ - grid[x][0] += grid[x - 1][0]; - } - - for(int y = 1; y < my ; y++){ - grid[0][y] += grid[0][y - 1]; - } - - for(int x = 1; x < mx; x++){ - for(int y = 1; y < my; y++){ - grid[x][y] += Math.min(grid[x - 1][y], grid[x][y - 1]); - } - } - - return grid[mx - 1][my - 1]; - } +public class Solution { + public int minPathSum(int[][] grid) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + + int mx = grid.length; + if(mx == 0) return 0; + + int my = grid[0].length; + + for(int x = 1; x < mx ; x++){ + grid[x][0] += grid[x - 1][0]; + } + + for(int y = 1; y < my ; y++){ + grid[0][y] += grid[0][y - 1]; + } + + for(int x = 1; x < mx; x++){ + for(int y = 1; y < my; y++){ + grid[x][y] += Math.min(grid[x - 1][y], grid[x][y - 1]); + } + } + + return grid[mx - 1][my - 1]; + } } \ No newline at end of file diff --git a/_includes/_root/minimum-window-substring/Solution.java b/_includes/_root/minimum-window-substring/Solution.java index 493407f..bf5ad7b 100644 --- a/_includes/_root/minimum-window-substring/Solution.java +++ b/_includes/_root/minimum-window-substring/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - public String minWindow(String S, String T) { - char[] s = S.toCharArray(); - char[] t = T.toCharArray(); - - if ( t.length == 0) return ""; - if ( t.length > s.length ) return ""; - - - int mstart = 0; - int mend = -1; - - int gstart = 0; - int gend = 0; - - int[] need = new int[256]; - int[] seen = new int[256]; - - int checksum = 0; - - for(char c : t){ - need[(int)c]++; - } - - for(/*void*/; gend < s.length; gend++ ){ - - int i = (int)s[gend]; - if(need[i] > 0){ - seen[i]++; - - if(seen[i] <= need[i]) - checksum++; - } - - - if(checksum == t.length){ - - if(mend < 0) mend = s.length - 1; - - for(/*void*/; gstart <= gend; gstart++){ - - i = (int)s[gstart]; - if(need[i] > 0){ - if( seen[i] > need[i] ){ - seen[i]--; - } else { - break; - } - } - } - - if(gend - gstart < mend - mstart ){ - mstart = gstart; - mend = gend; - } - - } - - } - - - return S.substring(mstart, mend + 1); - } +public class Solution { + public String minWindow(String S, String T) { + char[] s = S.toCharArray(); + char[] t = T.toCharArray(); + + if ( t.length == 0) return ""; + if ( t.length > s.length ) return ""; + + + int mstart = 0; + int mend = -1; + + int gstart = 0; + int gend = 0; + + int[] need = new int[256]; + int[] seen = new int[256]; + + int checksum = 0; + + for(char c : t){ + need[(int)c]++; + } + + for(/*void*/; gend < s.length; gend++ ){ + + int i = (int)s[gend]; + if(need[i] > 0){ + seen[i]++; + + if(seen[i] <= need[i]) + checksum++; + } + + + if(checksum == t.length){ + + if(mend < 0) mend = s.length - 1; + + for(/*void*/; gstart <= gend; gstart++){ + + i = (int)s[gstart]; + if(need[i] > 0){ + if( seen[i] > need[i] ){ + seen[i]--; + } else { + break; + } + } + } + + if(gend - gstart < mend - mstart ){ + mstart = gstart; + mend = gend; + } + + } + + } + + + return S.substring(mstart, mend + 1); + } } \ No newline at end of file diff --git a/_includes/_root/missing-ranges/README.md b/_includes/_root/missing-ranges/README.md index 69aaf0c..1c0fb88 100644 --- a/_includes/_root/missing-ranges/README.md +++ b/_includes/_root/missing-ranges/README.md @@ -1,63 +1,63 @@ -## Loop invariant - -init range is lower -> upper - -when a new number comes, the number divide the range into two ranges. -the left range must be a missing range. just output it. - - -``` -R = [0 -> 99] -S = [0, 1, 3, 50, 75] - ^ - | -``` - -`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` - -``` -R = [1 -> 99] -S = [1, 3, 50, 75] - ^ - | -``` - -`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` - -``` -R = [2 -> 99] -S = [3, 50, 75] - ^ - | -``` - -`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` - -`[2]` is a missing, output. - - -``` -R = [4 -> 99] -S = [50, 75] - ^ - | -``` - -`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` - -`[4 -> 49]` is a missing, output. - - -``` -R = [51 -> 99] -S = [75] - ^ - | -``` - -`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` - -`[51 -> 74]` is a missing, output. - - -the last one `[76 -> 99]` is a missing range too. +## Loop invariant + +init range is lower -> upper + +when a new number comes, the number divide the range into two ranges. +the left range must be a missing range. just output it. + + +``` +R = [0 -> 99] +S = [0, 1, 3, 50, 75] + ^ + | +``` + +`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` + +``` +R = [1 -> 99] +S = [1, 3, 50, 75] + ^ + | +``` + +`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` + +``` +R = [2 -> 99] +S = [3, 50, 75] + ^ + | +``` + +`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` + +`[2]` is a missing, output. + + +``` +R = [4 -> 99] +S = [50, 75] + ^ + | +``` + +`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` + +`[4 -> 49]` is a missing, output. + + +``` +R = [51 -> 99] +S = [75] + ^ + | +``` + +`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` + +`[51 -> 74]` is a missing, output. + + +the last one `[76 -> 99]` is a missing range too. diff --git a/_includes/_root/multiply-strings/Solution.java b/_includes/_root/multiply-strings/Solution.java index 7d2309d..b77b33e 100644 --- a/_includes/_root/multiply-strings/Solution.java +++ b/_includes/_root/multiply-strings/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public String multiply(String num1, String num2) { - - int[] paper = new int[num1.length() + num2.length()]; - - Arrays.fill(paper, 0); - - char[] _num1 = num1.toCharArray(); - char[] _num2 = num2.toCharArray(); - - for (int i = 0; i < _num2.length; i++) { - for (int j = 0; j < _num1.length; j++) { - paper[paper.length - (i + j + 2)] += (_num1[j] - '0') * (_num2[i] - '0'); - } - } - - - // add - - for (int i = 0; i < paper.length - 1; i++) { - paper[i + 1] += paper[i] / 10; - paper[i] %= 10; - - } - - String s = ""; - for(int i = paper.length - 1; i > 0 ; i--){ - - if(paper[i] == 0 && "".equals(s)) - continue; - - s += paper[i]; - } - - s += paper[0]; - - - return s; - - } +public class Solution { + public String multiply(String num1, String num2) { + + int[] paper = new int[num1.length() + num2.length()]; + + Arrays.fill(paper, 0); + + char[] _num1 = num1.toCharArray(); + char[] _num2 = num2.toCharArray(); + + for (int i = 0; i < _num2.length; i++) { + for (int j = 0; j < _num1.length; j++) { + paper[paper.length - (i + j + 2)] += (_num1[j] - '0') * (_num2[i] - '0'); + } + } + + + // add + + for (int i = 0; i < paper.length - 1; i++) { + paper[i + 1] += paper[i] / 10; + paper[i] %= 10; + + } + + String s = ""; + for(int i = paper.length - 1; i > 0 ; i--){ + + if(paper[i] == 0 && "".equals(s)) + continue; + + s += paper[i]; + } + + s += paper[0]; + + + return s; + + } } \ No newline at end of file diff --git a/_includes/_root/n-queens-ii/Solution.java b/_includes/_root/n-queens-ii/Solution.java index 7af34ef..ff737b8 100644 --- a/_includes/_root/n-queens-ii/Solution.java +++ b/_includes/_root/n-queens-ii/Solution.java @@ -1,58 +1,58 @@ -public class Solution { - - boolean[][] chessboard; - - int target; - - int rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - rt++; - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public int totalNQueens(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - chessboard = new boolean[n][n]; - target = n - 1; - - rt = 0; - - search(0); - - return rt; - } +public class Solution { + + boolean[][] chessboard; + + int target; + + int rt; + + boolean tryput(final int row, final int col){ + for(int i = row - 1; i >= 0; i--){ + int offset = row - i; + if(chessboard[i][col]) + return false; + + if(col - offset >= 0 && chessboard[i][col - offset]) + return false; + + if(col + offset <= target && chessboard[i][col + offset]) + return false; + } + + return true; + } + + void search(final int row){ + + if( row > target){ + + rt++; + + return; + } + + for(int i = 0; i <= target ; i++){ + if(tryput(row, i)){ + + chessboard[row][i] = true; + + search(row + 1); + + chessboard[row][i] = false; + } + } + + } + + public int totalNQueens(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + chessboard = new boolean[n][n]; + target = n - 1; + + rt = 0; + + search(0); + + return rt; + } } \ No newline at end of file diff --git a/_includes/_root/n-queens/Solution.java b/_includes/_root/n-queens/Solution.java index d6ff48b..7f28524 100644 --- a/_includes/_root/n-queens/Solution.java +++ b/_includes/_root/n-queens/Solution.java @@ -1,67 +1,67 @@ -public class Solution { - boolean[][] chessboard; - - int target; - - ArrayList rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - String[] valid = new String[target + 1]; - - for(int i = 0; i <= target ; i++){ - char[] s = new char[target + 1]; - for(int j = 0; j <= target; j++){ - s[j] = chessboard[i][j] ? 'Q' : '.'; - } - - valid[i] = new String(s); - } - - rt.add(valid); - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public List solveNQueens(int n) { - chessboard = new boolean[n][n]; - target = n - 1; - - rt = new ArrayList(); - - search(0); - - return rt; - } -} +public class Solution { + boolean[][] chessboard; + + int target; + + ArrayList rt; + + boolean tryput(final int row, final int col){ + for(int i = row - 1; i >= 0; i--){ + int offset = row - i; + if(chessboard[i][col]) + return false; + + if(col - offset >= 0 && chessboard[i][col - offset]) + return false; + + if(col + offset <= target && chessboard[i][col + offset]) + return false; + } + + return true; + } + + void search(final int row){ + + if( row > target){ + + String[] valid = new String[target + 1]; + + for(int i = 0; i <= target ; i++){ + char[] s = new char[target + 1]; + for(int j = 0; j <= target; j++){ + s[j] = chessboard[i][j] ? 'Q' : '.'; + } + + valid[i] = new String(s); + } + + rt.add(valid); + + return; + } + + for(int i = 0; i <= target ; i++){ + if(tryput(row, i)){ + + chessboard[row][i] = true; + + search(row + 1); + + chessboard[row][i] = false; + } + } + + } + + public List solveNQueens(int n) { + chessboard = new boolean[n][n]; + target = n - 1; + + rt = new ArrayList(); + + search(0); + + return rt; + } +} diff --git a/_includes/_root/next-permutation/Solution.java b/_includes/_root/next-permutation/Solution.java index b7d1b34..e0166e2 100644 --- a/_includes/_root/next-permutation/Solution.java +++ b/_includes/_root/next-permutation/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - // http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public void nextPermutation(int[] num) { - - if(num.length < 2) return; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - } +public class Solution { + // http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html + void swap(int x[], int a, int b) { + int t = x[a]; + x[a] = x[b]; + x[b] = t; + } + + public void nextPermutation(int[] num) { + + if(num.length < 2) return; + + int p = -1; + + for(int i = num.length - 1; i >0; i--){ + if(num[i] > num[i - 1]){ + p = i - 1; + break; + } + } + + if(p == -1){ + Arrays.sort(num); + return; + } + + int c = -1; + for(int i = num.length - 1; i >=0; i--){ + if(num[i] > num[p]) { + c = i; + break; + } + } + + swap(num, p, c); + Arrays.sort(num, p + 1, num.length); + + } } \ No newline at end of file diff --git a/_includes/_root/one-edit-distance/README.md b/_includes/_root/one-edit-distance/README.md index 26004a9..2c95d72 100644 --- a/_includes/_root/one-edit-distance/README.md +++ b/_includes/_root/one-edit-distance/README.md @@ -1,26 +1,26 @@ -## [Edit Distance](../edit-distance) == 1 - -My first submission - - -``` -return minDistance(s, t) == 1; -``` - -but, leetcode shows `time limit exceeded`. - - -## Only 1 diff - -### Same length - -do one pass can know if there is only one different char - -### 1 char longer - -delete the redundant char will yield two same string - -Note: - -solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. - +## [Edit Distance](../edit-distance) == 1 + +My first submission + + +``` +return minDistance(s, t) == 1; +``` + +but, leetcode shows `time limit exceeded`. + + +## Only 1 diff + +### Same length + +do one pass can know if there is only one different char + +### 1 char longer + +delete the redundant char will yield two same string + +Note: + +solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. + diff --git a/_includes/_root/palindrome-number/Solution.java b/_includes/_root/palindrome-number/Solution.java index 074e10c..8578bb7 100644 --- a/_includes/_root/palindrome-number/Solution.java +++ b/_includes/_root/palindrome-number/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public boolean isPalindrome(int x) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - - if(x < 0) return false; - - if(x == 0) return true; - - int size = (int)Math.log10(x); - - int mid = size / 2; - - for(int i = 0; i <= mid; i++){ - - int p = (int) (x / Math.pow(10, i)) % 10; - int q = (int) (x / Math.pow(10, size - i)) % 10; - if(p != q) - return false; - - } - - return true; - } +public class Solution { + public boolean isPalindrome(int x) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + + if(x < 0) return false; + + if(x == 0) return true; + + int size = (int)Math.log10(x); + + int mid = size / 2; + + for(int i = 0; i <= mid; i++){ + + int p = (int) (x / Math.pow(10, i)) % 10; + int q = (int) (x / Math.pow(10, size - i)) % 10; + if(p != q) + return false; + + } + + return true; + } } \ No newline at end of file diff --git a/_includes/_root/palindrome-partitioning-ii/Solution.java b/_includes/_root/palindrome-partitioning-ii/Solution.java index 61922b0..d34fffd 100644 --- a/_includes/_root/palindrome-partitioning-ii/Solution.java +++ b/_includes/_root/palindrome-partitioning-ii/Solution.java @@ -1,49 +1,49 @@ -public class Solution { - public int minCut(String s) { - char[] S = s.toCharArray(); - - if(S.length == 0) return 0; - - boolean[][] P = new boolean[S.length][S.length]; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - P[2 - 1][i] = S[i] == S[i + 2 - 1]; - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - P[len - 1][i] = P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]; - } - } - - int[] mincut = new int[S.length + 1]; - - mincut[0] = 0; - mincut[1] = 0; - - for(int len = 2; len <= S.length; len++){ - - if(P[len - 1][0]){ - mincut[len] = 0; - }else{ - - mincut[len] = mincut[len - 1] + 1; - - for(int i = 1; i < len - 1; i++){ - - if(P[len - i - 1][i]){ - mincut[len] = Math.min(mincut[i] + 1 , mincut[len]); - } - } - } - } - - return mincut[S.length]; - } -} +public class Solution { + public int minCut(String s) { + char[] S = s.toCharArray(); + + if(S.length == 0) return 0; + + boolean[][] P = new boolean[S.length][S.length]; + + // len 1 + Arrays.fill(P[1 - 1], true); + + // len 2 + for(int i = 0; i < S.length - 1; i++){ + P[2 - 1][i] = S[i] == S[i + 2 - 1]; + } + + // len 3 to max + for(int len = 3; len <= S.length; len++){ + + for(int i = 0; i < S.length - (len - 1); i++){ + P[len - 1][i] = P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]; + } + } + + int[] mincut = new int[S.length + 1]; + + mincut[0] = 0; + mincut[1] = 0; + + for(int len = 2; len <= S.length; len++){ + + if(P[len - 1][0]){ + mincut[len] = 0; + }else{ + + mincut[len] = mincut[len - 1] + 1; + + for(int i = 1; i < len - 1; i++){ + + if(P[len - i - 1][i]){ + mincut[len] = Math.min(mincut[i] + 1 , mincut[len]); + } + } + } + } + + return mincut[S.length]; + } +} diff --git a/_includes/_root/palindrome-partitioning/Solution.java b/_includes/_root/palindrome-partitioning/Solution.java index 98a651e..db94c57 100644 --- a/_includes/_root/palindrome-partitioning/Solution.java +++ b/_includes/_root/palindrome-partitioning/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - boolean isPal(String s){ - - char[] S = s.toCharArray(); - - for(int i = 0; i < S.length / 2; i++){ - if(S[i] != S[S.length - i - 1]) - return false; - } - - return true; - } - - - - public List> partition(String s) { - - List> rt = new ArrayList>(); - - if("".equals(s)) return rt; - if(s.length() == 1) return Arrays.asList(Arrays.asList(s)); - - for(int i = 0; i < s.length(); i++){ - String x = s.substring(0, i + 1); - if(isPal(x)){ - List> sub = partition(s.substring(i + 1)); - - if(sub.isEmpty()){ - rt.add(Arrays.asList(x)); - } else { - for(List l : sub){ - ArrayList _l = new ArrayList(); - _l.add(x); - _l.addAll(l); - rt.add(_l); - } - } - } - } - - return rt; - - } +public class Solution { + + boolean isPal(String s){ + + char[] S = s.toCharArray(); + + for(int i = 0; i < S.length / 2; i++){ + if(S[i] != S[S.length - i - 1]) + return false; + } + + return true; + } + + + + public List> partition(String s) { + + List> rt = new ArrayList>(); + + if("".equals(s)) return rt; + if(s.length() == 1) return Arrays.asList(Arrays.asList(s)); + + for(int i = 0; i < s.length(); i++){ + String x = s.substring(0, i + 1); + if(isPal(x)){ + List> sub = partition(s.substring(i + 1)); + + if(sub.isEmpty()){ + rt.add(Arrays.asList(x)); + } else { + for(List l : sub){ + ArrayList _l = new ArrayList(); + _l.add(x); + _l.addAll(l); + rt.add(_l); + } + } + } + } + + return rt; + + } } \ No newline at end of file diff --git a/_includes/_root/partition-list/Solution.java b/_includes/_root/partition-list/Solution.java index a0abea8..4580a4b 100644 --- a/_includes/_root/partition-list/Solution.java +++ b/_includes/_root/partition-list/Solution.java @@ -1,43 +1,43 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode partition(ListNode head, int x) { - if(head == null) return null; - if(head.next == null) return head; - - final ListNode less = new ListNode(0); - final ListNode greater = new ListNode(0); - - ListNode _less = less; - ListNode _greater = greater; - - while(head != null){ - ListNode t = head; - head = head.next; - - if(t.val < x){ - _less.next = t; - _less = _less.next; - }else { - _greater.next = t; - _greater = _greater.next; - } - } - - _greater.next = null; - - _less.next = greater.next; - - return less.next; - - } -} +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode partition(ListNode head, int x) { + if(head == null) return null; + if(head.next == null) return head; + + final ListNode less = new ListNode(0); + final ListNode greater = new ListNode(0); + + ListNode _less = less; + ListNode _greater = greater; + + while(head != null){ + ListNode t = head; + head = head.next; + + if(t.val < x){ + _less.next = t; + _less = _less.next; + }else { + _greater.next = t; + _greater = _greater.next; + } + } + + _greater.next = null; + + _less.next = greater.next; + + return less.next; + + } +} diff --git a/_includes/_root/pascals-triangle-ii/Solution.java b/_includes/_root/pascals-triangle-ii/Solution.java index 86aefa4..dd8a4ba 100644 --- a/_includes/_root/pascals-triangle-ii/Solution.java +++ b/_includes/_root/pascals-triangle-ii/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public List getRow(int rowIndex) { - Integer[] row = new Integer[rowIndex + 1]; - - Arrays.fill(row, 1); - - for(int i = 0 ; i < rowIndex - 1; i++){ - for(int j = i + 1; j >= 1; j--){ - row[j] = row[j] + row[j - 1]; - } - } - - return Arrays.asList(row); - } -} +public class Solution { + public List getRow(int rowIndex) { + Integer[] row = new Integer[rowIndex + 1]; + + Arrays.fill(row, 1); + + for(int i = 0 ; i < rowIndex - 1; i++){ + for(int j = i + 1; j >= 1; j--){ + row[j] = row[j] + row[j - 1]; + } + } + + return Arrays.asList(row); + } +} diff --git a/_includes/_root/pascals-triangle/Solution.java b/_includes/_root/pascals-triangle/Solution.java index 77ad926..503e03d 100644 --- a/_includes/_root/pascals-triangle/Solution.java +++ b/_includes/_root/pascals-triangle/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public List> generate(int numRows) { - - ArrayList> rt = new ArrayList>(); - - Integer[] prev = null; - - for(int i = 1 ; i <= numRows; i++){ - - Integer[] row = new Integer[i]; - - row[0] = 1; - row[i - 1] = 1; - - for(int j = 1; j < i - 1 ; j++){ - //row.add(j, prev.get(j) + prev.get(j -1)); - row[j] = prev[j] + prev[j - 1]; - } - - rt.add(new ArrayList(Arrays.asList(row))); - prev = row; - } - - - return rt; - - } -} +public class Solution { + public List> generate(int numRows) { + + ArrayList> rt = new ArrayList>(); + + Integer[] prev = null; + + for(int i = 1 ; i <= numRows; i++){ + + Integer[] row = new Integer[i]; + + row[0] = 1; + row[i - 1] = 1; + + for(int j = 1; j < i - 1 ; j++){ + //row.add(j, prev.get(j) + prev.get(j -1)); + row[j] = prev[j] + prev[j - 1]; + } + + rt.add(new ArrayList(Arrays.asList(row))); + prev = row; + } + + + return rt; + + } +} diff --git a/_includes/_root/path-sum-ii/Solution.java b/_includes/_root/path-sum-ii/Solution.java index c3186f2..ab9ab8a 100644 --- a/_includes/_root/path-sum-ii/Solution.java +++ b/_includes/_root/path-sum-ii/Solution.java @@ -1,44 +1,44 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - void addIfNotEmpty(List> rt, List> l){ - if(!l.isEmpty()){ - rt.addAll(l); - } - } - - List> pathSum(TreeNode root, int sum, List parents) { - List> rt = new ArrayList>(); - - if(root == null) return rt; - - ArrayList p = new ArrayList(parents); - p.add(root.val); - - if(root.left == null & root.right == null){ - if(root.val == sum){ - rt.add(p); - } - - return rt; - } - - addIfNotEmpty(rt, pathSum(root.left, sum - root.val, p)); - addIfNotEmpty(rt, pathSum(root.right, sum - root.val, p)); - - return rt; - } - - public List> pathSum(TreeNode root, int sum) { - - return pathSum(root, sum, new ArrayList()); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + void addIfNotEmpty(List> rt, List> l){ + if(!l.isEmpty()){ + rt.addAll(l); + } + } + + List> pathSum(TreeNode root, int sum, List parents) { + List> rt = new ArrayList>(); + + if(root == null) return rt; + + ArrayList p = new ArrayList(parents); + p.add(root.val); + + if(root.left == null & root.right == null){ + if(root.val == sum){ + rt.add(p); + } + + return rt; + } + + addIfNotEmpty(rt, pathSum(root.left, sum - root.val, p)); + addIfNotEmpty(rt, pathSum(root.right, sum - root.val, p)); + + return rt; + } + + public List> pathSum(TreeNode root, int sum) { + + return pathSum(root, sum, new ArrayList()); + } +} diff --git a/_includes/_root/path-sum/Solution.java b/_includes/_root/path-sum/Solution.java index aef077b..02715bf 100644 --- a/_includes/_root/path-sum/Solution.java +++ b/_includes/_root/path-sum/Solution.java @@ -1,27 +1,27 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - - - public boolean hasPathSum(TreeNode root, int sum) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (root == null) - return false; - - if (root.left == null && root.right == null) //leaf - return root.val == sum; - - return (root.left != null && hasPathSum(root.left, sum - root.val)) - || (root.right != null && hasPathSum(root.right, sum - root.val)); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + + + public boolean hasPathSum(TreeNode root, int sum) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if (root == null) + return false; + + if (root.left == null && root.right == null) //leaf + return root.val == sum; + + return (root.left != null && hasPathSum(root.left, sum - root.val)) + || (root.right != null && hasPathSum(root.right, sum - root.val)); + } } \ No newline at end of file diff --git a/_includes/_root/permutation-sequence/Solution.java b/_includes/_root/permutation-sequence/Solution.java index 7348fe2..ce7abe3 100644 --- a/_includes/_root/permutation-sequence/Solution.java +++ b/_includes/_root/permutation-sequence/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - - int fact(int x){ - int s = 1; - - for(int i = 1; i <= x; i++) - s *= i; - - return s; - } - - public String getPermutation(int n, int k) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ArrayList chars = new ArrayList(); - - for(int i = '1'; i <('1' + n); i++) - chars.add((char)i); - - k -= 1; - - char[] t = new char[n]; - int l = 0; - - for(int i = n - 1; i > 0; i--){ - int f = fact(i); - - int c = k / f; - - t[l++] = chars.get(c); - chars.remove(c); - - k %= f; - } - - t[n - 1] = chars.get(0); - - return new String(t); - - } +public class Solution { + + int fact(int x){ + int s = 1; + + for(int i = 1; i <= x; i++) + s *= i; + + return s; + } + + public String getPermutation(int n, int k) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ArrayList chars = new ArrayList(); + + for(int i = '1'; i <('1' + n); i++) + chars.add((char)i); + + k -= 1; + + char[] t = new char[n]; + int l = 0; + + for(int i = n - 1; i > 0; i--){ + int f = fact(i); + + int c = k / f; + + t[l++] = chars.get(c); + chars.remove(c); + + k %= f; + } + + t[n - 1] = chars.get(0); + + return new String(t); + + } } \ No newline at end of file diff --git a/_includes/_root/permutations-ii/Solution.java b/_includes/_root/permutations-ii/Solution.java index eae0ae2..a0d2b4c 100644 --- a/_includes/_root/permutations-ii/Solution.java +++ b/_includes/_root/permutations-ii/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public boolean nextPermutation(int[] num) { - - if(num.length < 2) return false; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return false; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - return true; - } - - List asList(int[] num){ - ArrayList l = new ArrayList(num.length); - for(int i = 0; i < num.length; i++) - l.add(num[i]); - - return l; - } - - public List> permuteUnique(int[] num) { - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - found.add(asList(num)); - - while(nextPermutation(num)){ - found.add(asList(num)); - } - - return found; - } -} +public class Solution { + + void swap(int x[], int a, int b) { + int t = x[a]; + x[a] = x[b]; + x[b] = t; + } + + public boolean nextPermutation(int[] num) { + + if(num.length < 2) return false; + + int p = -1; + + for(int i = num.length - 1; i >0; i--){ + if(num[i] > num[i - 1]){ + p = i - 1; + break; + } + } + + if(p == -1){ + Arrays.sort(num); + return false; + } + + int c = -1; + for(int i = num.length - 1; i >=0; i--){ + if(num[i] > num[p]) { + c = i; + break; + } + } + + swap(num, p, c); + Arrays.sort(num, p + 1, num.length); + + return true; + } + + List asList(int[] num){ + ArrayList l = new ArrayList(num.length); + for(int i = 0; i < num.length; i++) + l.add(num[i]); + + return l; + } + + public List> permuteUnique(int[] num) { + Arrays.sort(num); + + ArrayList> found = new ArrayList>(); + found.add(asList(num)); + + while(nextPermutation(num)){ + found.add(asList(num)); + } + + return found; + } +} diff --git a/_includes/_root/permutations/Solution.java b/_includes/_root/permutations/Solution.java index b9112cc..a1e1ae7 100644 --- a/_includes/_root/permutations/Solution.java +++ b/_includes/_root/permutations/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - - int[] resetof(int[] num, int index){ - int[] rt = new int[num.length - 1]; - int s = 0; - for(int i = 0; i < num.length ; i++) - if(i != index) rt[s++] = num[i]; - - return rt; - } - - public List> permute(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if(num.length == 0){ - // do nothing - }else if(num.length == 1) { - rt.add(new ArrayList(Arrays.asList(num[0]))); - }else{ - - for(int i = 0; i < num.length; i++){ - for(List l : permute(resetof(num, i))){ - l.add(num[i]); - rt.add(l); - }; - } - - } - - return rt; - - - } -} +public class Solution { + + int[] resetof(int[] num, int index){ + int[] rt = new int[num.length - 1]; + int s = 0; + for(int i = 0; i < num.length ; i++) + if(i != index) rt[s++] = num[i]; + + return rt; + } + + public List> permute(int[] num) { + + ArrayList> rt = new ArrayList>(); + + if(num.length == 0){ + // do nothing + }else if(num.length == 1) { + rt.add(new ArrayList(Arrays.asList(num[0]))); + }else{ + + for(int i = 0; i < num.length; i++){ + for(List l : permute(resetof(num, i))){ + l.add(num[i]); + rt.add(l); + }; + } + + } + + return rt; + + + } +} diff --git a/_includes/_root/plus-one/Solution.java b/_includes/_root/plus-one/Solution.java index 1908d68..e31cd2c 100644 --- a/_includes/_root/plus-one/Solution.java +++ b/_includes/_root/plus-one/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public int[] plusOne(int[] digits) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int[] result = new int[digits.length + 1]; - digits[digits.length - 1] += 1; - for(int i = digits.length - 1; i >=0 ; i--){ - result[ i + 1 ] += digits[i]; - result[ i ] += result[ i + 1 ] / 10; - result[ i + 1 ] %= 10; - } - - if(result[0] == 0) return Arrays.copyOfRange(result, 1 , result.length); - else - return result; - } +public class Solution { + public int[] plusOne(int[] digits) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + int[] result = new int[digits.length + 1]; + digits[digits.length - 1] += 1; + for(int i = digits.length - 1; i >=0 ; i--){ + result[ i + 1 ] += digits[i]; + result[ i ] += result[ i + 1 ] / 10; + result[ i + 1 ] %= 10; + } + + if(result[0] == 0) return Arrays.copyOfRange(result, 1 , result.length); + else + return result; + } } \ No newline at end of file diff --git a/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java b/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java index 8ed1a81..a470db6 100644 --- a/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java +++ b/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeLinkNode ORPHAN = new TreeLinkNode(0); - - TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){ - - if(parent == null) return null; - - if(parent.left != null && parent.left != me){ - return parent.left; - } - - if(parent.right != null){ - return parent.right; - } - - return sib(ORPHAN, parent.next); - - } - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - if(root.left != null){ - root.left.next = sib(root.left, root); - } - - - if(root.right != null){ - root.right.next = sib(ORPHAN, root.next); - } - - connect(root.right); - connect(root.left); - - - } +/** + * Definition for binary tree with next pointer. + * public class TreeLinkNode { + * int val; + * TreeLinkNode left, right, next; + * TreeLinkNode(int x) { val = x; } + * } + */ +public class Solution { + + static final TreeLinkNode ORPHAN = new TreeLinkNode(0); + + TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){ + + if(parent == null) return null; + + if(parent.left != null && parent.left != me){ + return parent.left; + } + + if(parent.right != null){ + return parent.right; + } + + return sib(ORPHAN, parent.next); + + } + + public void connect(TreeLinkNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null) return; + + if(root.left != null){ + root.left.next = sib(root.left, root); + } + + + if(root.right != null){ + root.right.next = sib(ORPHAN, root.next); + } + + connect(root.right); + connect(root.left); + + + } } \ No newline at end of file diff --git a/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java b/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java index 9c92d20..7dcfb82 100644 --- a/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java +++ b/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java @@ -1,26 +1,26 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null || root.left == null || root.right == null) return; - - root.left.next = root.right; - - if(root.next != null){ - root.right.next = root.next.left; - } - - connect(root.left); - connect(root.right); - - } +/** + * Definition for binary tree with next pointer. + * public class TreeLinkNode { + * int val; + * TreeLinkNode left, right, next; + * TreeLinkNode(int x) { val = x; } + * } + */ +public class Solution { + + + public void connect(TreeLinkNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null || root.left == null || root.right == null) return; + + root.left.next = root.right; + + if(root.next != null){ + root.right.next = root.next.left; + } + + connect(root.left); + connect(root.right); + + } } \ No newline at end of file diff --git a/_includes/_root/powx-n/Solution.java b/_includes/_root/powx-n/Solution.java index 54ffa89..f8e8026 100644 --- a/_includes/_root/powx-n/Solution.java +++ b/_includes/_root/powx-n/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public double pow(double x, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(n == 0) return 1; - - double s = pow(x, n /2); - - if(n % 2 == 0) - return s * s; - else if(n > 0) - return s * s * x; - else - return s * s / x; - - - } -} +public class Solution { + public double pow(double x, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(n == 0) return 1; + + double s = pow(x, n /2); + + if(n % 2 == 0) + return s * s; + else if(n > 0) + return s * s * x; + else + return s * s / x; + + + } +} diff --git a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md index 5118d2e..81e0be1 100644 --- a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md +++ b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md @@ -1,23 +1,23 @@ -## EAGAIN and read - -This is a common problem in real world. -when client read some data from server, data will not always be available to be read. -`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, -call me later. - -## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) - -when you call `read4`, it might return 4 `char`s. -however, the `read` only ask you for 1 `char`. -you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. - -to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. - -``` - | just store these two chars for coming read call - V - .... .... .... ..** .... .. -[++++ ++++ ++++ ++][ ++++ +] - -``` - +## EAGAIN and read + +This is a common problem in real world. +when client read some data from server, data will not always be available to be read. +`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, +call me later. + +## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) + +when you call `read4`, it might return 4 `char`s. +however, the `read` only ask you for 1 `char`. +you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. + +to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. + +``` + | just store these two chars for coming read call + V + .... .... .... ..** .... .. +[++++ ++++ ++++ ++][ ++++ +] + +``` + diff --git a/_includes/_root/read-n-characters-given-read4/README.md b/_includes/_root/read-n-characters-given-read4/README.md index 69203bc..40f4900 100644 --- a/_includes/_root/read-n-characters-given-read4/README.md +++ b/_includes/_root/read-n-characters-given-read4/README.md @@ -1,14 +1,14 @@ -## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full - - -``` -.... .... .... ...E <- data read4 -++++ ++++ ++++ ++ <- data pipe to read -``` - -code should be like below - -``` -while not EOF or buf not full - append read4 to buf -``` +## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full + + +``` +.... .... .... ...E <- data read4 +++++ ++++ ++++ ++ <- data pipe to read +``` + +code should be like below + +``` +while not EOF or buf not full + append read4 to buf +``` diff --git a/_includes/_root/recover-binary-search-tree/Solution.java b/_includes/_root/recover-binary-search-tree/Solution.java index dd2ef22..f3813ec 100644 --- a/_includes/_root/recover-binary-search-tree/Solution.java +++ b/_includes/_root/recover-binary-search-tree/Solution.java @@ -1,53 +1,53 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode[] bad; - TreeNode last; - - - void inorder(TreeNode root){ - - if(root.left != null) inorder(root.left); - - if(last != null && last.val > root.val){ // - bad[0] = root; - - if(bad[1] == null) bad[1] = last; - } - - last = root; - - - if(root.right != null) inorder(root.right); - - } - - public void recoverTree(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - bad = new TreeNode[2]; - bad[0] = null; - bad[1] = null; - last = null; - - inorder(root); - - - if(bad[0] != null && bad[1] != null){ - int t = bad[0].val; - bad[0].val = bad[1].val; - bad[1].val = t; - } - - - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode[] bad; + TreeNode last; + + + void inorder(TreeNode root){ + + if(root.left != null) inorder(root.left); + + if(last != null && last.val > root.val){ // + bad[0] = root; + + if(bad[1] == null) bad[1] = last; + } + + last = root; + + + if(root.right != null) inorder(root.right); + + } + + public void recoverTree(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null) return; + + bad = new TreeNode[2]; + bad[0] = null; + bad[1] = null; + last = null; + + inorder(root); + + + if(bad[0] != null && bad[1] != null){ + int t = bad[0].val; + bad[0].val = bad[1].val; + bad[1].val = t; + } + + + } } \ No newline at end of file diff --git a/_includes/_root/regular-expression-matching/Solution.java b/_includes/_root/regular-expression-matching/Solution.java index 6b997d4..3140552 100644 --- a/_includes/_root/regular-expression-matching/Solution.java +++ b/_includes/_root/regular-expression-matching/Solution.java @@ -1,232 +1,232 @@ -public class Solution { - static final Character EPSILON = 0; - - static class State{ - - static Set allchar = new HashSet(); - - boolean end; - - Map> next = new HashMap>(); - - State(){ - this(false); - } - - State(boolean end){ - this.end = end; - } - - State match(Character c) { - Set states = next.get(c); - - if(states == null){ - states = next.get('.'); - } - - if(states != null) { - for (State s : states) { - return s; - } - } - - return null; - } - - Set matchAll(Character c) { - Set match = next.get(c); - - return match; - } - - void addNext(Character c, State s){ - - if(c != EPSILON) - allchar.add(c); - - Set l = next.get(c); - - if(l == null){ - l = new HashSet(); - next.put(c, l); - } - - l.add(s); - } - } - - State nfa(char[] pattern){ - - final State end = new State(true); - - State last = end; - - for(int i = pattern.length - 1; i >= 0; i--){ - if(pattern[i] == '*'){ - i--; - - State s1 = new State(); - State s2 = new State(); - State s3 = new State(); - State s4 = last; - - s1.addNext(EPSILON, s2); - s1.addNext(EPSILON, s4); - - s2.addNext(pattern[i], s3); - - s3.addNext(EPSILON, s4); - - s4.addNext(EPSILON, s2); - - last = s1; - - }else{ - State curr = new State(); - curr.addNext(pattern[i], last); - last = curr; - } - } - - - return last; - } - - boolean end(Set states){ - for (State state : states) { - if(state.end){ - return true; - } - } - return false; - } - - State dfa(State start){ - - Map, HashMap>> table = new HashMap, HashMap>>(); - Map, State> toone = new HashMap, State>(); - - final Set enter = allEpslilon(Collections.singleton(start)); - - LinkedList> queue = new LinkedList>(); - queue.add(enter); - - while(!queue.isEmpty()){ - - Set key = queue.poll(); - - if(!toone.containsKey(key)){ - State maps = new State(); - maps.end = end(key); - - toone.put(key, maps); - } - - HashMap> targets = searchTarget(key); - table.put(key, targets); - - for (Set states : targets.values()) { - if(table.get(states) == null){ - queue.add(states); - } - } - - } - - for (Map.Entry, HashMap>> entry : table.entrySet()) { - State s = toone.get(entry.getKey()); - - for (Map.Entry> t : entry.getValue().entrySet()) { - s.addNext(t.getKey(), toone.get(t.getValue())); - } - - } - - return toone.get(enter); - } - - HashMap> searchTarget(Set form) { - HashMap> targets = new HashMap>(); - - for(State s : form) { - for (Character c : State.allchar) { - Set ns = s.matchAll(c); - - if (ns == null) continue; - - Set states = allEpslilon(ns); - - Set t = targets.get(c); - if(t == null){ - t = new HashSet(); - targets.put(c, t); - } - - t.addAll(states); - - } - } - - return targets; - } - - Set allEpslilon(Set ns) { - Set states = new HashSet(); - states.addAll(ns); - - - int oldsize = 0; - - - while (states.size() != oldsize) { - - oldsize = states.size(); - - Set temp = new HashSet(); - - for (State target : states) { - Set t = target.matchAll(EPSILON); - if (t != null) temp.addAll(t); - } - - states.addAll(temp); - - } - return states; - } - - boolean isMatch(char[] s, State state, int p){ - - if(state == null){ - return false; - } - - if(p >= s.length){ - return state.end; - } - - for (Map.Entry> entry : state.next.entrySet()) { - - Character key = entry.getKey(); - if(key.equals(s[p]) || key.equals('.')){ - if(isMatch(s, entry.getValue().iterator().next(), p + 1)){ - return true; - } - } - } - - return false; - } - - public boolean isMatch(String s, String p) { - - State.allchar = new HashSet(); - - State state = nfa(p.toCharArray()); - state = dfa(state); - - char[] chars = s.toCharArray(); - - return isMatch(chars, state, 0); - } +public class Solution { + static final Character EPSILON = 0; + + static class State{ + + static Set allchar = new HashSet(); + + boolean end; + + Map> next = new HashMap>(); + + State(){ + this(false); + } + + State(boolean end){ + this.end = end; + } + + State match(Character c) { + Set states = next.get(c); + + if(states == null){ + states = next.get('.'); + } + + if(states != null) { + for (State s : states) { + return s; + } + } + + return null; + } + + Set matchAll(Character c) { + Set match = next.get(c); + + return match; + } + + void addNext(Character c, State s){ + + if(c != EPSILON) + allchar.add(c); + + Set l = next.get(c); + + if(l == null){ + l = new HashSet(); + next.put(c, l); + } + + l.add(s); + } + } + + State nfa(char[] pattern){ + + final State end = new State(true); + + State last = end; + + for(int i = pattern.length - 1; i >= 0; i--){ + if(pattern[i] == '*'){ + i--; + + State s1 = new State(); + State s2 = new State(); + State s3 = new State(); + State s4 = last; + + s1.addNext(EPSILON, s2); + s1.addNext(EPSILON, s4); + + s2.addNext(pattern[i], s3); + + s3.addNext(EPSILON, s4); + + s4.addNext(EPSILON, s2); + + last = s1; + + }else{ + State curr = new State(); + curr.addNext(pattern[i], last); + last = curr; + } + } + + + return last; + } + + boolean end(Set states){ + for (State state : states) { + if(state.end){ + return true; + } + } + return false; + } + + State dfa(State start){ + + Map, HashMap>> table = new HashMap, HashMap>>(); + Map, State> toone = new HashMap, State>(); + + final Set enter = allEpslilon(Collections.singleton(start)); + + LinkedList> queue = new LinkedList>(); + queue.add(enter); + + while(!queue.isEmpty()){ + + Set key = queue.poll(); + + if(!toone.containsKey(key)){ + State maps = new State(); + maps.end = end(key); + + toone.put(key, maps); + } + + HashMap> targets = searchTarget(key); + table.put(key, targets); + + for (Set states : targets.values()) { + if(table.get(states) == null){ + queue.add(states); + } + } + + } + + for (Map.Entry, HashMap>> entry : table.entrySet()) { + State s = toone.get(entry.getKey()); + + for (Map.Entry> t : entry.getValue().entrySet()) { + s.addNext(t.getKey(), toone.get(t.getValue())); + } + + } + + return toone.get(enter); + } + + HashMap> searchTarget(Set form) { + HashMap> targets = new HashMap>(); + + for(State s : form) { + for (Character c : State.allchar) { + Set ns = s.matchAll(c); + + if (ns == null) continue; + + Set states = allEpslilon(ns); + + Set t = targets.get(c); + if(t == null){ + t = new HashSet(); + targets.put(c, t); + } + + t.addAll(states); + + } + } + + return targets; + } + + Set allEpslilon(Set ns) { + Set states = new HashSet(); + states.addAll(ns); + + + int oldsize = 0; + + + while (states.size() != oldsize) { + + oldsize = states.size(); + + Set temp = new HashSet(); + + for (State target : states) { + Set t = target.matchAll(EPSILON); + if (t != null) temp.addAll(t); + } + + states.addAll(temp); + + } + return states; + } + + boolean isMatch(char[] s, State state, int p){ + + if(state == null){ + return false; + } + + if(p >= s.length){ + return state.end; + } + + for (Map.Entry> entry : state.next.entrySet()) { + + Character key = entry.getKey(); + if(key.equals(s[p]) || key.equals('.')){ + if(isMatch(s, entry.getValue().iterator().next(), p + 1)){ + return true; + } + } + } + + return false; + } + + public boolean isMatch(String s, String p) { + + State.allchar = new HashSet(); + + State state = nfa(p.toCharArray()); + state = dfa(state); + + char[] chars = s.toCharArray(); + + return isMatch(chars, state, 0); + } } \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java b/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java index 4e9e4bb..54ca064 100644 --- a/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java +++ b/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java @@ -1,25 +1,25 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(A.length == 0) return 0; - - int len = 1; - int lastseencount = 0; - - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]){ - - for(int j = i - 1; j > len + Math.min(lastseencount, 1) - 1 ; j--) - A[j] = A[i]; - - len += Math.min(lastseencount, 1) + 1; - lastseencount = 0; - }else{ - lastseencount++; - } - } - - return len + Math.min(lastseencount, 1); - } +public class Solution { + public int removeDuplicates(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(A.length == 0) return 0; + + int len = 1; + int lastseencount = 0; + + for(int i = 1; i< A.length; i++){ + if(A[i] != A[i - 1]){ + + for(int j = i - 1; j > len + Math.min(lastseencount, 1) - 1 ; j--) + A[j] = A[i]; + + len += Math.min(lastseencount, 1) + 1; + lastseencount = 0; + }else{ + lastseencount++; + } + } + + return len + Math.min(lastseencount, 1); + } } \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-array/Solution.java b/_includes/_root/remove-duplicates-from-sorted-array/Solution.java index bc6acb4..3edcc3e 100644 --- a/_includes/_root/remove-duplicates-from-sorted-array/Solution.java +++ b/_includes/_root/remove-duplicates-from-sorted-array/Solution.java @@ -1,19 +1,19 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if (A.length == 0) return 0; - - int len = 1; - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]) { - for(int j = i - 1 ; j > len - 1 ; j-- ) - A[j] = A[i]; - - len++; - } - } - - return len; - } +public class Solution { + public int removeDuplicates(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if (A.length == 0) return 0; + + int len = 1; + for(int i = 1; i< A.length; i++){ + if(A[i] != A[i - 1]) { + for(int j = i - 1 ; j > len - 1 ; j-- ) + A[j] = A[i]; + + len++; + } + } + + return len; + } } \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java b/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java index 2c5121d..06e5fec 100644 --- a/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java +++ b/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java @@ -1,37 +1,37 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head; - - boolean killme = false; - while(node.next != null && node.next.val == v){ - node = node.next; - killme = true; - } - - if(killme) - head = deleteDuplicates(node.next); - else - head.next = deleteDuplicates(node.next); - - return head; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode deleteDuplicates(ListNode head) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + if(head.next == null) return head; + + int v = head.val; + + ListNode node = head; + + boolean killme = false; + while(node.next != null && node.next.val == v){ + node = node.next; + killme = true; + } + + if(killme) + head = deleteDuplicates(node.next); + else + head.next = deleteDuplicates(node.next); + + return head; + + } } \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-list/Solution.java b/_includes/_root/remove-duplicates-from-sorted-list/Solution.java index 9c78398..badf567 100644 --- a/_includes/_root/remove-duplicates-from-sorted-list/Solution.java +++ b/_includes/_root/remove-duplicates-from-sorted-list/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head.next; - ListNode lasthead = head; - while(node != null){ - - while(node != null && node.val == lasthead.val) node = node.next; - - lasthead.next = node; - lasthead = node; - - if(node != null) node = node.next; - - } - - return head; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode deleteDuplicates(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return null; + if(head.next == null) return head; + + int v = head.val; + + ListNode node = head.next; + ListNode lasthead = head; + while(node != null){ + + while(node != null && node.val == lasthead.val) node = node.next; + + lasthead.next = node; + lasthead = node; + + if(node != null) node = node.next; + + } + + return head; + } } \ No newline at end of file diff --git a/_includes/_root/remove-element/Solution.java b/_includes/_root/remove-element/Solution.java index a632df9..fe31570 100644 --- a/_includes/_root/remove-element/Solution.java +++ b/_includes/_root/remove-element/Solution.java @@ -1,16 +1,16 @@ -public class Solution { - public int removeElement(int[] A, int elem) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(A.length == 0) return 0; - - int len = 0; - - for(int i = 0; i< A.length; i++){ - if(A[i] != elem) A[len++] = A[i]; - } - - - return len; - } +public class Solution { + public int removeElement(int[] A, int elem) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(A.length == 0) return 0; + + int len = 0; + + for(int i = 0; i< A.length; i++){ + if(A[i] != elem) A[len++] = A[i]; + } + + + return len; + } } \ No newline at end of file diff --git a/_includes/_root/remove-nth-node-from-end-of-list/Solution.java b/_includes/_root/remove-nth-node-from-end-of-list/Solution.java index 4998282..063465a 100644 --- a/_includes/_root/remove-nth-node-from-end-of-list/Solution.java +++ b/_includes/_root/remove-nth-node-from-end-of-list/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - final ListNode _head = new ListNode(0); - _head.next = head; - - ListNode fast = _head; - ListNode slow = _head; - - for(int i = 0; i< n ; i++) fast = fast.next; - - while(fast != null && fast.next != null){ - fast = fast.next; - slow = slow.next; - } - - slow.next = slow.next.next; - - return _head.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + final ListNode _head = new ListNode(0); + _head.next = head; + + ListNode fast = _head; + ListNode slow = _head; + + for(int i = 0; i< n ; i++) fast = fast.next; + + while(fast != null && fast.next != null){ + fast = fast.next; + slow = slow.next; + } + + slow.next = slow.next.next; + + return _head.next; + } } \ No newline at end of file diff --git a/_includes/_root/reorder-list/Solution.java b/_includes/_root/reorder-list/Solution.java index b6fa642..547df74 100644 --- a/_includes/_root/reorder-list/Solution.java +++ b/_includes/_root/reorder-list/Solution.java @@ -1,75 +1,75 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode reverse(ListNode head){ - ListNode prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode mid(ListNode head){ - - ListNode fast = head; - ListNode slow = head; - - while(fast != null && fast.next != null){ - fast = fast.next.next; - slow = slow.next; - } - - return slow; - } - - public void reorderList(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return; - if(head.next == null) return; - - ListNode left = head; - - ListNode mid = mid(head); - - ListNode right = mid.next; - - if(right == null) return; - - mid.next = null; - - right = reverse(right); - - while(head != null){ - ListNode t = head.next; - - ListNode r = right; - - if(r == null) return; - - head.next = r; - right = right.next; - r.next = t; - - head = t; - } - - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + ListNode reverse(ListNode head){ + ListNode prev = null; + + while(head != null){ + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + + ListNode mid(ListNode head){ + + ListNode fast = head; + ListNode slow = head; + + while(fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + } + + return slow; + } + + public void reorderList(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return; + if(head.next == null) return; + + ListNode left = head; + + ListNode mid = mid(head); + + ListNode right = mid.next; + + if(right == null) return; + + mid.next = null; + + right = reverse(right); + + while(head != null){ + ListNode t = head.next; + + ListNode r = right; + + if(r == null) return; + + head.next = r; + right = right.next; + r.next = t; + + head = t; + } + + } } \ No newline at end of file diff --git a/_includes/_root/restore-ip-addresses/Solution.java b/_includes/_root/restore-ip-addresses/Solution.java index cd549f8..97f46f4 100644 --- a/_includes/_root/restore-ip-addresses/Solution.java +++ b/_includes/_root/restore-ip-addresses/Solution.java @@ -1,46 +1,46 @@ -public class Solution { - - ArrayList collect; - - String[] stack; - - void findnum(String s, int p, int pstack){ - - if(pstack == 4){ - - if(p >= s.length()){ - String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; - - collect.add(ip); - } - - return; - } - - for(int i = 1; i <= 3; i++){ - - if( p + i > s.length()) - return; - - String number = s.substring(p, p + i); - - if(i > 1 && s.charAt(p) == '0') continue; - - if(Integer.parseInt(number) <= 255){ - stack[pstack] = number; - findnum(s, p + i, pstack + 1); - } - - } - } - - public List restoreIpAddresses(String s) { - - collect = new ArrayList(); - stack = new String[4]; - - findnum(s, 0 , 0); - - return collect; - } -} +public class Solution { + + ArrayList collect; + + String[] stack; + + void findnum(String s, int p, int pstack){ + + if(pstack == 4){ + + if(p >= s.length()){ + String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; + + collect.add(ip); + } + + return; + } + + for(int i = 1; i <= 3; i++){ + + if( p + i > s.length()) + return; + + String number = s.substring(p, p + i); + + if(i > 1 && s.charAt(p) == '0') continue; + + if(Integer.parseInt(number) <= 255){ + stack[pstack] = number; + findnum(s, p + i, pstack + 1); + } + + } + } + + public List restoreIpAddresses(String s) { + + collect = new ArrayList(); + stack = new String[4]; + + findnum(s, 0 , 0); + + return collect; + } +} diff --git a/_includes/_root/reverse-integer/Solution.java b/_includes/_root/reverse-integer/Solution.java index d9b4d6e..7d0fb3c 100644 --- a/_includes/_root/reverse-integer/Solution.java +++ b/_includes/_root/reverse-integer/Solution.java @@ -1,23 +1,23 @@ -public class Solution { - public int reverse(int x) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(x == 0) return 0; - if(x < 0) return -reverse(-x); - - int len = (int)Math.log10(x) + 1; - int[] y = new int[len]; - - int i = 0; - while(i < len){ - y[i] = x % 10; - x /= 10; - i++; - } - - int s = 0; - for(i = len - 1; i >=0 ; i--) - s += y[i] * Math.pow(10, len - 1 - i); - - return s; - } +public class Solution { + public int reverse(int x) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(x == 0) return 0; + if(x < 0) return -reverse(-x); + + int len = (int)Math.log10(x) + 1; + int[] y = new int[len]; + + int i = 0; + while(i < len){ + y[i] = x % 10; + x /= 10; + i++; + } + + int s = 0; + for(i = len - 1; i >=0 ; i--) + s += y[i] * Math.pow(10, len - 1 - i); + + return s; + } } \ No newline at end of file diff --git a/_includes/_root/reverse-linked-list-ii/Solution.java b/_includes/_root/reverse-linked-list-ii/Solution.java index 8c4db87..519f910 100644 --- a/_includes/_root/reverse-linked-list-ii/Solution.java +++ b/_includes/_root/reverse-linked-list-ii/Solution.java @@ -1,64 +1,64 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseBetween(ListNode head, int m, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int c = 1; - - final ListNode _head = head; - - ListNode prev = null; - - ListNode jointLeft = null; - ListNode jointRight = null; - - while(head != null){ - - ListNode t = head.next; - - if(c == m){ - jointLeft = prev; - jointRight = head; - } - - if(c >= m && c <= n){ - head.next = prev; - } - - prev = head; - head = t; - - if(c == n){ - if(jointLeft != null){ - jointLeft.next = prev; - } - jointRight.next = head; - - if(jointRight == _head){ - return prev; - }else{ - return _head; - } - } - - c++; - - } - - return _head; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode reverseBetween(ListNode head, int m, int n) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + if(head.next == null) return head; + + int c = 1; + + final ListNode _head = head; + + ListNode prev = null; + + ListNode jointLeft = null; + ListNode jointRight = null; + + while(head != null){ + + ListNode t = head.next; + + if(c == m){ + jointLeft = prev; + jointRight = head; + } + + if(c >= m && c <= n){ + head.next = prev; + } + + prev = head; + head = t; + + if(c == n){ + if(jointLeft != null){ + jointLeft.next = prev; + } + jointRight.next = head; + + if(jointRight == _head){ + return prev; + }else{ + return _head; + } + } + + c++; + + } + + return _head; + } } \ No newline at end of file diff --git a/_includes/_root/reverse-nodes-in-k-group/Solution.java b/_includes/_root/reverse-nodes-in-k-group/Solution.java index c9330fc..739b608 100644 --- a/_includes/_root/reverse-nodes-in-k-group/Solution.java +++ b/_includes/_root/reverse-nodes-in-k-group/Solution.java @@ -1,57 +1,57 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseKGroup(ListNode head, int k) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(k <= 1) return head; - - if(head == null) return null; - if(head.next == null) return head; - - ListNode tail = head; - ListNode prev = null; - - for(int i = 0; i < k ; i++){ - if(head == null){ - - // rollback - head = prev; - prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - tail.next = reverseKGroup(head, k); - - return prev; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(k <= 1) return head; + + if(head == null) return null; + if(head.next == null) return head; + + ListNode tail = head; + ListNode prev = null; + + for(int i = 0; i < k ; i++){ + if(head == null){ + + // rollback + head = prev; + prev = null; + + while(head != null){ + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + tail.next = reverseKGroup(head, k); + + return prev; + + } } \ No newline at end of file diff --git a/_includes/_root/reverse-words-in-a-string/Solution.java b/_includes/_root/reverse-words-in-a-string/Solution.java index 4e61b34..b760659 100644 --- a/_includes/_root/reverse-words-in-a-string/Solution.java +++ b/_includes/_root/reverse-words-in-a-string/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - public String reverseWords(String s) { - if(s == null) return null; - - - ArrayList words = new ArrayList(); - - StringBuilder buff = new StringBuilder(); - - for(char c : (s + " ").toCharArray()){ - if (c != ' '){ - buff.append(c); - }else{ - String w = buff.toString(); - if(!"".equals(w)){ - words.add(w); - buff = new StringBuilder(); - } - } - } - - if(words.size() == 0) return ""; - - buff = new StringBuilder(); - for(int i = words.size() - 1; i >0 ; i--){ - buff.append(words.get(i)); - buff.append(' '); - } - - buff.append(words.get(0)); - - return buff.toString(); - - } +public class Solution { + public String reverseWords(String s) { + if(s == null) return null; + + + ArrayList words = new ArrayList(); + + StringBuilder buff = new StringBuilder(); + + for(char c : (s + " ").toCharArray()){ + if (c != ' '){ + buff.append(c); + }else{ + String w = buff.toString(); + if(!"".equals(w)){ + words.add(w); + buff = new StringBuilder(); + } + } + } + + if(words.size() == 0) return ""; + + buff = new StringBuilder(); + for(int i = words.size() - 1; i >0 ; i--){ + buff.append(words.get(i)); + buff.append(' '); + } + + buff.append(words.get(0)); + + return buff.toString(); + + } } \ No newline at end of file diff --git a/_includes/_root/roman-to-integer/Solution.java b/_includes/_root/roman-to-integer/Solution.java index a059b41..de87539 100644 --- a/_includes/_root/roman-to-integer/Solution.java +++ b/_includes/_root/roman-to-integer/Solution.java @@ -1,55 +1,55 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - int index(char c){ - for(int i = 0 ; i < C.length; i++){ - if (C[i] == c) - return i; - } - - return -1; - } - - int rtoi(char c){ - return N[index(c)]; - } - - public int romanToInt(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s.length() <= 0) return 0; - - char[] cs = s.toCharArray(); - - int sum = rtoi(cs[0]); - - for (int i = 1 ; i < cs.length; i++){ - sum += rtoi(cs[i]); - - int j = i - 1; - int ci = index(cs[i]); - - while(j>=0 && index(cs[j]) < ci){ - sum -= rtoi(cs[j--]) * 2; - } - } - - - return sum; - } +public class Solution { + + /* + http://en.wikipedia.org/wiki/Roman_numerals + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1,000 + + to avoid four characters being repeated in succession + */ + + static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; + static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; + + int index(char c){ + for(int i = 0 ; i < C.length; i++){ + if (C[i] == c) + return i; + } + + return -1; + } + + int rtoi(char c){ + return N[index(c)]; + } + + public int romanToInt(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(s.length() <= 0) return 0; + + char[] cs = s.toCharArray(); + + int sum = rtoi(cs[0]); + + for (int i = 1 ; i < cs.length; i++){ + sum += rtoi(cs[i]); + + int j = i - 1; + int ci = index(cs[i]); + + while(j>=0 && index(cs[j]) < ci){ + sum -= rtoi(cs[j--]) * 2; + } + } + + + return sum; + } } \ No newline at end of file diff --git a/_includes/_root/rotate-image/Solution.java b/_includes/_root/rotate-image/Solution.java index 221b2ef..f35fecd 100644 --- a/_includes/_root/rotate-image/Solution.java +++ b/_includes/_root/rotate-image/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public void rotate(int[][] matrix) { - - - final int mx = matrix.length; - final int my = matrix[0].length; - int x,y; - - int t; - - int _my = my - 1; - for(x = 0; x < mx - 1; x++){ - for(y = 0; y < _my; y++){ - int ny = mx - 1 - x; - int nx = my - 1 - y; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - - } - _my--; - } - - - for(x = 0; x < mx ; x++){ - for(y = 0 ; y < my / 2; y++){ - int ny = my - 1 - y; - int nx = x; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - } - } - - } +public class Solution { + public void rotate(int[][] matrix) { + + + final int mx = matrix.length; + final int my = matrix[0].length; + int x,y; + + int t; + + int _my = my - 1; + for(x = 0; x < mx - 1; x++){ + for(y = 0; y < _my; y++){ + int ny = mx - 1 - x; + int nx = my - 1 - y; + + t = matrix[y][x]; + matrix[y][x] = matrix[ny][nx]; + matrix[ny][nx] = t; + + } + _my--; + } + + + for(x = 0; x < mx ; x++){ + for(y = 0 ; y < my / 2; y++){ + int ny = my - 1 - y; + int nx = x; + + t = matrix[y][x]; + matrix[y][x] = matrix[ny][nx]; + matrix[ny][nx] = t; + } + } + + } } \ No newline at end of file diff --git a/_includes/_root/rotate-list/Solution.java b/_includes/_root/rotate-list/Solution.java index a5081c6..efb2005 100644 --- a/_includes/_root/rotate-list/Solution.java +++ b/_includes/_root/rotate-list/Solution.java @@ -1,41 +1,41 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode rotateRight(ListNode head, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - ListNode _head = head; - - ListNode node = head; - int len = 1; - while(node.next != null){ - len++; - node = node.next; - } - - n %= len; - - ListNode tail = node; - - node = head; - for(int i = 0; i < len - n - 1; i++) node = node.next; - - tail.next = head; - ListNode rt = node.next; - node.next = null; - - return rt; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode rotateRight(ListNode head, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + + ListNode _head = head; + + ListNode node = head; + int len = 1; + while(node.next != null){ + len++; + node = node.next; + } + + n %= len; + + ListNode tail = node; + + node = head; + for(int i = 0; i < len - n - 1; i++) node = node.next; + + tail.next = head; + ListNode rt = node.next; + node.next = null; + + return rt; + + } } \ No newline at end of file diff --git a/_includes/_root/same-tree/Solution.java b/_includes/_root/same-tree/Solution.java index 602741d..a5806c2 100644 --- a/_includes/_root/same-tree/Solution.java +++ b/_includes/_root/same-tree/Solution.java @@ -1,21 +1,21 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - - if(p == null && q == null){ - return true; - }else if(p == null || q == null){ - return false; - } - - return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + + if(p == null && q == null){ + return true; + }else if(p == null || q == null){ + return false; + } + + return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } } \ No newline at end of file diff --git a/_includes/_root/scramble-string/Solution.java b/_includes/_root/scramble-string/Solution.java index 0ee6504..7323b3c 100644 --- a/_includes/_root/scramble-string/Solution.java +++ b/_includes/_root/scramble-string/Solution.java @@ -1,173 +1,173 @@ -public class Solution { - - static class Board { - - HashMap left = new HashMap(); - HashMap right = new HashMap(); - - String leftString; - String rightString; - - HashMap part(int idx){ - if(idx < left.size()){ - return left; - } else { - return right; - } - - } - - void add(Map m, Character c){ - Integer cnt = m.get(c); - - if(cnt == null){ - m.put(c, 1); - return; - } - - m.put(c, cnt + 1); - - } - - void addLeft(Character c){ - add(left, c); - } - - void addRight(Character c){ - add(right, c); - } - - int count(Map m, Character c){ - Integer cnt = m.get(c); - if(cnt == null) return 0; - - return cnt; - } - - boolean hasChar(int idx, Character c, int count){ - - HashMap m = part(idx); - - if(m == left){ - return count(m, c) >= count; - } - - return count(left, c) + count(right, c) >= count; - } - } - - List buildTwo(char[] all, int p){ - - Board b = new Board(); - - StringBuilder leftString = new StringBuilder(); - StringBuilder rightString = new StringBuilder(); - - for(int i = 0; i < all.length; i++){ - - Character c = all[i]; - if(i < p){ - leftString.append(c); - b.addLeft(c); - }else{ - rightString.append(c); - b.addRight(c); - } - } - - b.leftString = leftString.toString(); - b.rightString = rightString.toString(); - - Board mb = new Board(); - mb.left = new HashMap(b.right); - mb.right = new HashMap(b.left); - - mb.leftString = b.rightString; - mb.rightString = b.leftString; - - return Arrays.asList(new Board[]{b, mb}); - } - - boolean checkSameChar(char[] s1, char[] s2){ - s1 = Arrays.copyOf(s1, s1.length); - s2 = Arrays.copyOf(s2, s2.length); - - Arrays.sort(s1); - Arrays.sort(s2); - return Arrays.equals(s1, s2); - } - - static final Board SEP = new Board(); - - public boolean isScramble(String s1, String s2) { - - char[] _s1 = s1.toCharArray(); - char[] _s2 = s2.toCharArray(); - - if(_s1.length != _s2.length) - return false; - - if(_s1.length == 0) return true; - if(_s1.length == 1) return _s1[0] == _s2[0]; - if(!checkSameChar(_s1, _s2)) - return false; - - - LinkedList exp = new LinkedList(); - - for(int i = 1; i < _s1.length; i++){ - exp.addAll(buildTwo(_s1, i)); - } - - exp.add(SEP); - - HashMap counting = new HashMap(); - - for(int i = 0; i < _s2.length; i++){ - - Character c = _s2[i]; - - Integer cnt = counting.get(c); - - if(cnt == null){ - cnt = 0; - counting.put(c, 1); - }else{ - counting.put(c, cnt + 1); - } - - while(true){ - Board b = exp.poll(); - - if(b == SEP){ - if(exp.isEmpty()) - return false; - - exp.add(SEP); - break; - } - - if(b.hasChar(i, c, cnt + 1)){ - exp.add(b); - } - - } - - } - - for(Board b : exp){ - if(b != SEP){ - - if(isScramble(b.leftString , s2.substring(0, b.leftString.length()) ) - && isScramble(b.rightString, s2.substring(b.leftString.length()))) { - return true; - } - - } - } - - return false; - - } - +public class Solution { + + static class Board { + + HashMap left = new HashMap(); + HashMap right = new HashMap(); + + String leftString; + String rightString; + + HashMap part(int idx){ + if(idx < left.size()){ + return left; + } else { + return right; + } + + } + + void add(Map m, Character c){ + Integer cnt = m.get(c); + + if(cnt == null){ + m.put(c, 1); + return; + } + + m.put(c, cnt + 1); + + } + + void addLeft(Character c){ + add(left, c); + } + + void addRight(Character c){ + add(right, c); + } + + int count(Map m, Character c){ + Integer cnt = m.get(c); + if(cnt == null) return 0; + + return cnt; + } + + boolean hasChar(int idx, Character c, int count){ + + HashMap m = part(idx); + + if(m == left){ + return count(m, c) >= count; + } + + return count(left, c) + count(right, c) >= count; + } + } + + List buildTwo(char[] all, int p){ + + Board b = new Board(); + + StringBuilder leftString = new StringBuilder(); + StringBuilder rightString = new StringBuilder(); + + for(int i = 0; i < all.length; i++){ + + Character c = all[i]; + if(i < p){ + leftString.append(c); + b.addLeft(c); + }else{ + rightString.append(c); + b.addRight(c); + } + } + + b.leftString = leftString.toString(); + b.rightString = rightString.toString(); + + Board mb = new Board(); + mb.left = new HashMap(b.right); + mb.right = new HashMap(b.left); + + mb.leftString = b.rightString; + mb.rightString = b.leftString; + + return Arrays.asList(new Board[]{b, mb}); + } + + boolean checkSameChar(char[] s1, char[] s2){ + s1 = Arrays.copyOf(s1, s1.length); + s2 = Arrays.copyOf(s2, s2.length); + + Arrays.sort(s1); + Arrays.sort(s2); + return Arrays.equals(s1, s2); + } + + static final Board SEP = new Board(); + + public boolean isScramble(String s1, String s2) { + + char[] _s1 = s1.toCharArray(); + char[] _s2 = s2.toCharArray(); + + if(_s1.length != _s2.length) + return false; + + if(_s1.length == 0) return true; + if(_s1.length == 1) return _s1[0] == _s2[0]; + if(!checkSameChar(_s1, _s2)) + return false; + + + LinkedList exp = new LinkedList(); + + for(int i = 1; i < _s1.length; i++){ + exp.addAll(buildTwo(_s1, i)); + } + + exp.add(SEP); + + HashMap counting = new HashMap(); + + for(int i = 0; i < _s2.length; i++){ + + Character c = _s2[i]; + + Integer cnt = counting.get(c); + + if(cnt == null){ + cnt = 0; + counting.put(c, 1); + }else{ + counting.put(c, cnt + 1); + } + + while(true){ + Board b = exp.poll(); + + if(b == SEP){ + if(exp.isEmpty()) + return false; + + exp.add(SEP); + break; + } + + if(b.hasChar(i, c, cnt + 1)){ + exp.add(b); + } + + } + + } + + for(Board b : exp){ + if(b != SEP){ + + if(isScramble(b.leftString , s2.substring(0, b.leftString.length()) ) + && isScramble(b.rightString, s2.substring(b.leftString.length()))) { + return true; + } + + } + } + + return false; + + } + } \ No newline at end of file diff --git a/_includes/_root/search-a-2d-matrix/Solution.java b/_includes/_root/search-a-2d-matrix/Solution.java index 2acf68e..f40c863 100644 --- a/_includes/_root/search-a-2d-matrix/Solution.java +++ b/_includes/_root/search-a-2d-matrix/Solution.java @@ -1,30 +1,30 @@ -public class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = matrix.length; - int my = matrix[0].length; - - final int count = mx * my; - - int l = 0, r = count; - - while(l < r){ - int m = (r + l) / 2; - - int x = m / my; - int y = m % my; - - if(matrix[x][y] == target) - return true; - else if(matrix[x][y] < target) - l = m + 1; - else - r = m; - - - } - - return false; - } +public class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int mx = matrix.length; + int my = matrix[0].length; + + final int count = mx * my; + + int l = 0, r = count; + + while(l < r){ + int m = (r + l) / 2; + + int x = m / my; + int y = m % my; + + if(matrix[x][y] == target) + return true; + else if(matrix[x][y] < target) + l = m + 1; + else + r = m; + + + } + + return false; + } } \ No newline at end of file diff --git a/_includes/_root/search-for-a-range/Solution.java b/_includes/_root/search-for-a-range/Solution.java index 72156a8..01bd046 100644 --- a/_includes/_root/search-for-a-range/Solution.java +++ b/_includes/_root/search-for-a-range/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - public int[] searchRange(int[] A, int target) { - - int s = 0, e = A.length; - - while( s < e ){ - int mid = (s + e) / 2; - - if(A[mid] == target){ - - int _s = mid, _e = mid; - - while(_s - 1 >= 0 && A[_s - 1] == target) _s--; - while(_e + 1 < A.length && A[_e + 1] == target) _e++; - - return new int[]{_s, _e}; - - }else if(A[mid] < target){ - s = mid + 1; - }else if(A[mid] > target){ - e = mid; - } - - } - - return new int[]{-1, -1}; - - } +public class Solution { + public int[] searchRange(int[] A, int target) { + + int s = 0, e = A.length; + + while( s < e ){ + int mid = (s + e) / 2; + + if(A[mid] == target){ + + int _s = mid, _e = mid; + + while(_s - 1 >= 0 && A[_s - 1] == target) _s--; + while(_e + 1 < A.length && A[_e + 1] == target) _e++; + + return new int[]{_s, _e}; + + }else if(A[mid] < target){ + s = mid + 1; + }else if(A[mid] > target){ + e = mid; + } + + } + + return new int[]{-1, -1}; + + } } \ No newline at end of file diff --git a/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java b/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java index 269b8da..fea9221 100644 --- a/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java +++ b/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java @@ -1,60 +1,60 @@ -public class Solution { - public boolean search(int[] A, int target) { - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return true; - } - - if(target < A[mid]){ - // normal in first half - if (A[s] == A[mid]) { - if(A[mid] == A[e - 1]){ - // special - - s++; - e--; - - }else{ - s = mid + 1; - } - - } else if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - if (A[mid] == A[e - 1]) { - if(A[s] == A[mid]){ - s++; - e--; - }else{ - e = mid; - } - - - } else if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return false; - } +public class Solution { + public boolean search(int[] A, int target) { + int s = 0; + int e = A.length; + + while(s < e){ + int mid = (s + e) /2; + + if(A[mid] == target){ + return true; + } + + if(target < A[mid]){ + // normal in first half + if (A[s] == A[mid]) { + if(A[mid] == A[e - 1]){ + // special + + s++; + e--; + + }else{ + s = mid + 1; + } + + } else if(A[s] <= A[mid] && A[s] <= target){ + e = mid; + // abnormal + }else if(A[mid] <= A[e - 1]){ + e = mid; + }else { + s = mid + 1; + } + + } else { + + // normal in last half + if (A[mid] == A[e - 1]) { + if(A[s] == A[mid]){ + s++; + e--; + }else{ + e = mid; + } + + + } else if(A[mid] <= A[e - 1] && target <= A[e - 1]){ + s = mid + 1; + } else if(A[s] <= A[mid]) { + s = mid + 1; + } else { + e = mid; + } + + } + } + + return false; + } } \ No newline at end of file diff --git a/_includes/_root/search-in-rotated-sorted-array/Solution.java b/_includes/_root/search-in-rotated-sorted-array/Solution.java index cd47ebd..b185f3c 100644 --- a/_includes/_root/search-in-rotated-sorted-array/Solution.java +++ b/_includes/_root/search-in-rotated-sorted-array/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int search(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return mid; - } - - if(target < A[mid]){ - // normal in first half - - if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - - if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return -1; - } +public class Solution { + public int search(int[] A, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + int s = 0; + int e = A.length; + + while(s < e){ + int mid = (s + e) /2; + + if(A[mid] == target){ + return mid; + } + + if(target < A[mid]){ + // normal in first half + + if(A[s] <= A[mid] && A[s] <= target){ + e = mid; + // abnormal + }else if(A[mid] <= A[e - 1]){ + e = mid; + }else { + s = mid + 1; + } + + } else { + + // normal in last half + + if(A[mid] <= A[e - 1] && target <= A[e - 1]){ + s = mid + 1; + } else if(A[s] <= A[mid]) { + s = mid + 1; + } else { + e = mid; + } + + } + } + + return -1; + } } \ No newline at end of file diff --git a/_includes/_root/search-insert-position/Solution.java b/_includes/_root/search-insert-position/Solution.java index 86d9b2a..a47f99b 100644 --- a/_includes/_root/search-insert-position/Solution.java +++ b/_includes/_root/search-insert-position/Solution.java @@ -1,9 +1,9 @@ -public class Solution { - public int searchInsert(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - for(int i = 0; i < A.length; i++){ - if(A[i] >= target) return i; - } - return A.length; - } +public class Solution { + public int searchInsert(int[] A, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + for(int i = 0; i < A.length; i++){ + if(A[i] >= target) return i; + } + return A.length; + } } \ No newline at end of file diff --git a/_includes/_root/set-matrix-zeroes/Solution.java b/_includes/_root/set-matrix-zeroes/Solution.java index 0d0969b..09d5995 100644 --- a/_includes/_root/set-matrix-zeroes/Solution.java +++ b/_includes/_root/set-matrix-zeroes/Solution.java @@ -1,65 +1,65 @@ -public class Solution { - public void setZeroes(int[][] matrix) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(matrix == null) return; - int mx = matrix.length; - if ( mx == 0) return; - int my = matrix[0].length; - - int x, y; - - boolean xfz = false, yfz = false; - - for(x = 0; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - xfz = true; - break; - } - } - - for(y = 0; y < my ; y++ ){ - if(matrix[0][y] == 0){ - yfz = true; - break; - } - } - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my ; y++){ - if(matrix[x][y] == 0){ - matrix[x][0] = 0; - matrix[0][y] = 0; - } - } - } - - for(x = 1; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - for(y = 0; y < my; y++){ - matrix[x][y] = 0; - } - } - } - - for(y = 1; y < my ; y++ ){ - if(matrix[0][y] == 0){ - for(x = 0; x < mx; x++){ - matrix[x][y] = 0; - } - } - } - - if(xfz){ - for(x = 0; x < mx ; x++ ){ - matrix[x][0] = 0; - } - } - - if(yfz){ - for(y = 0; y < my ; y++ ){ - matrix[0][y] = 0; - } - } - } +public class Solution { + public void setZeroes(int[][] matrix) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(matrix == null) return; + int mx = matrix.length; + if ( mx == 0) return; + int my = matrix[0].length; + + int x, y; + + boolean xfz = false, yfz = false; + + for(x = 0; x < mx ; x++ ){ + if(matrix[x][0] == 0){ + xfz = true; + break; + } + } + + for(y = 0; y < my ; y++ ){ + if(matrix[0][y] == 0){ + yfz = true; + break; + } + } + + for(x = 1; x < mx ; x++){ + for(y = 1; y < my ; y++){ + if(matrix[x][y] == 0){ + matrix[x][0] = 0; + matrix[0][y] = 0; + } + } + } + + for(x = 1; x < mx ; x++ ){ + if(matrix[x][0] == 0){ + for(y = 0; y < my; y++){ + matrix[x][y] = 0; + } + } + } + + for(y = 1; y < my ; y++ ){ + if(matrix[0][y] == 0){ + for(x = 0; x < mx; x++){ + matrix[x][y] = 0; + } + } + } + + if(xfz){ + for(x = 0; x < mx ; x++ ){ + matrix[x][0] = 0; + } + } + + if(yfz){ + for(y = 0; y < my ; y++ ){ + matrix[0][y] = 0; + } + } + } } \ No newline at end of file diff --git a/_includes/_root/simplify-path/Solution.java b/_includes/_root/simplify-path/Solution.java index 035b98d..fb04589 100644 --- a/_includes/_root/simplify-path/Solution.java +++ b/_includes/_root/simplify-path/Solution.java @@ -1,44 +1,44 @@ -public class Solution { - public String simplifyPath(String path) { - - String[] names = path.split("/"); - - int eat = 0; - - LinkedList stack = new LinkedList(); - - for(int i = names.length - 1; i >= 0; i--){ - - String token = names[i]; - - if("..".equals(token)){ - eat++; - }else if(".".equals(token)){ - // do nothing - }else if("".equals(token)){ - // do nothing - }else { - - // dir name - if(eat > 0){ - eat--; - }else{ - stack.push(token); - } - } - } - - StringBuilder s = new StringBuilder(); - - s.append("/"); - - while(stack.size() > 1){ - s.append(stack.pop()); - s.append("/"); - } - - if(!stack.isEmpty()) s.append(stack.pop()); - - return s.toString(); - } -} +public class Solution { + public String simplifyPath(String path) { + + String[] names = path.split("/"); + + int eat = 0; + + LinkedList stack = new LinkedList(); + + for(int i = names.length - 1; i >= 0; i--){ + + String token = names[i]; + + if("..".equals(token)){ + eat++; + }else if(".".equals(token)){ + // do nothing + }else if("".equals(token)){ + // do nothing + }else { + + // dir name + if(eat > 0){ + eat--; + }else{ + stack.push(token); + } + } + } + + StringBuilder s = new StringBuilder(); + + s.append("/"); + + while(stack.size() > 1){ + s.append(stack.pop()); + s.append("/"); + } + + if(!stack.isEmpty()) s.append(stack.pop()); + + return s.toString(); + } +} diff --git a/_includes/_root/single-number-ii/Solution.java b/_includes/_root/single-number-ii/Solution.java index df011a8..eae2915 100644 --- a/_includes/_root/single-number-ii/Solution.java +++ b/_includes/_root/single-number-ii/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[] count = new int[Integer.SIZE]; - int[] bit = new int[Integer.SIZE]; - - Arrays.fill(count, 0); - Arrays.fill(bit, 0); - - for(int a : A){ - - for(int b = 0; b < Integer.SIZE; b++){ - int x = a >>> b & 1; - bit[b] |= x; - - if(x == 1) - count[b]++; - } - - } - - int s = 0; - for(int b = 0; b < Integer.SIZE; b++ ){ - if (count[b] % 3 != 0) - s |= bit[b] << b; - } - - return s; - - } +public class Solution { + public int singleNumber(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int[] count = new int[Integer.SIZE]; + int[] bit = new int[Integer.SIZE]; + + Arrays.fill(count, 0); + Arrays.fill(bit, 0); + + for(int a : A){ + + for(int b = 0; b < Integer.SIZE; b++){ + int x = a >>> b & 1; + bit[b] |= x; + + if(x == 1) + count[b]++; + } + + } + + int s = 0; + for(int b = 0; b < Integer.SIZE; b++ ){ + if (count[b] % 3 != 0) + s |= bit[b] << b; + } + + return s; + + } } \ No newline at end of file diff --git a/_includes/_root/single-number/Solution.java b/_includes/_root/single-number/Solution.java index efdb0d3..5d80c1c 100644 --- a/_includes/_root/single-number/Solution.java +++ b/_includes/_root/single-number/Solution.java @@ -1,13 +1,13 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if (A.length == 1) return A[0]; - int s = A[0]; - - for(int i = 1; i< A.length; i++) - s ^= A[i]; - - return s; - - } +public class Solution { + public int singleNumber(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if (A.length == 1) return A[0]; + int s = A[0]; + + for(int i = 1; i< A.length; i++) + s ^= A[i]; + + return s; + + } } \ No newline at end of file diff --git a/_includes/_root/sort-colors/Solution.java b/_includes/_root/sort-colors/Solution.java index 2460bee..3749c0e 100644 --- a/_includes/_root/sort-colors/Solution.java +++ b/_includes/_root/sort-colors/Solution.java @@ -1,36 +1,36 @@ -public class Solution { - public void sortColors(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int red = 0; - int blue = A.length - 1; - - int p = 0; - - int t = 0; - - while(p <= blue){ - - if(A[p] == 0){ //red - t = A[p]; - A[p] = A[red]; - A[red] = t; - - red++; - p++; - - }else if(A[p] == 2){ // blue - t = A[p]; - A[p] = A[blue]; - A[blue] = t; - - blue--; - }else{ // white - - p++; - - } - - } - } +public class Solution { + public void sortColors(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int red = 0; + int blue = A.length - 1; + + int p = 0; + + int t = 0; + + while(p <= blue){ + + if(A[p] == 0){ //red + t = A[p]; + A[p] = A[red]; + A[red] = t; + + red++; + p++; + + }else if(A[p] == 2){ // blue + t = A[p]; + A[p] = A[blue]; + A[blue] = t; + + blue--; + }else{ // white + + p++; + + } + + } + } } \ No newline at end of file diff --git a/_includes/_root/sort-list/Solution.java b/_includes/_root/sort-list/Solution.java index 6d942df..7407309 100644 --- a/_includes/_root/sort-list/Solution.java +++ b/_includes/_root/sort-list/Solution.java @@ -1,60 +1,60 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } - - - public ListNode sortList(ListNode head) { - if(head == null) return null; - if(head.next == null) return head; - - ListNode fast = head.next; - ListNode slow = head; - - while(fast != null && fast.next != null){ - slow = slow.next; - fast = fast.next.next; - } - - ListNode h2 = slow.next; - slow.next = null; - - return mergeTwoLists(sortList(head), sortList(h2)); - - - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + + + } + + + public ListNode sortList(ListNode head) { + if(head == null) return null; + if(head.next == null) return head; + + ListNode fast = head.next; + ListNode slow = head; + + while(fast != null && fast.next != null){ + slow = slow.next; + fast = fast.next.next; + } + + ListNode h2 = slow.next; + slow.next = null; + + return mergeTwoLists(sortList(head), sortList(h2)); + + + } } \ No newline at end of file diff --git a/_includes/_root/spiral-matrix-ii/Solution.java b/_includes/_root/spiral-matrix-ii/Solution.java index 0291cf1..0a30f2c 100644 --- a/_includes/_root/spiral-matrix-ii/Solution.java +++ b/_includes/_root/spiral-matrix-ii/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int[][] generateMatrix(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[][] rt = new int[n][n]; - if(n <= 0) return rt; - - int c = 1; - - int x = 0, y = 0, my = n , mx = n; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my; i++){ - rt[y][i] = c++; - } - - y++; - - for(int i = y; i < my && x < mx ; i++ ){ - rt[i][mx - 1] = c++; - } - - mx--; - - for(int i = mx - 1; i >= x && y < my; i--){ - rt[my - 1][i] = c++; - } - - my--; - - for(int i = my - 1; i>= y && x < mx; i--){ - rt[i][x] = c++; - } - - x++; - - } - - return rt; - - - } +public class Solution { + public int[][] generateMatrix(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int[][] rt = new int[n][n]; + if(n <= 0) return rt; + + int c = 1; + + int x = 0, y = 0, my = n , mx = n; + + while(x < mx && y < my){ + for(int i = x; i < mx && y < my; i++){ + rt[y][i] = c++; + } + + y++; + + for(int i = y; i < my && x < mx ; i++ ){ + rt[i][mx - 1] = c++; + } + + mx--; + + for(int i = mx - 1; i >= x && y < my; i--){ + rt[my - 1][i] = c++; + } + + my--; + + for(int i = my - 1; i>= y && x < mx; i--){ + rt[i][x] = c++; + } + + x++; + + } + + return rt; + + + } } \ No newline at end of file diff --git a/_includes/_root/spiral-matrix/Solution.java b/_includes/_root/spiral-matrix/Solution.java index ea8a38d..e4dc0ba 100644 --- a/_includes/_root/spiral-matrix/Solution.java +++ b/_includes/_root/spiral-matrix/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public List spiralOrder(int[][] matrix) { - ArrayList rt = new ArrayList(); - - if(matrix.length == 0) return rt; - - int x = 0, y = 0, my = matrix.length, mx = matrix[0].length; - //int dx = 1, dy = 1; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my ; i++){ - rt.add(matrix[y][i]); - } - - y++; - - for(int i = y; i< my && x < mx; i++){ - rt.add(matrix[i][mx - 1]); - } - - mx--; - - for(int i = mx - 1; i >= x && y < my ; i--){ - rt.add(matrix[my - 1][i]); - } - - my--; - - for(int i = my - 1; i >= y && x < mx; i--){ - rt.add(matrix[i][x]); - } - - x++; - - } - - - return rt; - - } -} +public class Solution { + public List spiralOrder(int[][] matrix) { + ArrayList rt = new ArrayList(); + + if(matrix.length == 0) return rt; + + int x = 0, y = 0, my = matrix.length, mx = matrix[0].length; + //int dx = 1, dy = 1; + + while(x < mx && y < my){ + for(int i = x; i < mx && y < my ; i++){ + rt.add(matrix[y][i]); + } + + y++; + + for(int i = y; i< my && x < mx; i++){ + rt.add(matrix[i][mx - 1]); + } + + mx--; + + for(int i = mx - 1; i >= x && y < my ; i--){ + rt.add(matrix[my - 1][i]); + } + + my--; + + for(int i = my - 1; i >= y && x < mx; i--){ + rt.add(matrix[i][x]); + } + + x++; + + } + + + return rt; + + } +} diff --git a/_includes/_root/sqrtx/Solution.java b/_includes/_root/sqrtx/Solution.java index c1d7706..0fb77d9 100644 --- a/_includes/_root/sqrtx/Solution.java +++ b/_includes/_root/sqrtx/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public int sqrt(int x) { - - if(x < 0) return -1; - if(x == 0) return 0; - - int s = 0; - int e = x; - - - while(s < e){ - int m = (e - s) / 2 + s; - - int m1 = x / (m + 1); - int m2 = x / (m + 1 + 1); - - if(m + 1 == m1){ - return m + 1; - } - - if(m + 1 + 1 == m2){ - return m + 1 + 1; - } - - if(m + 1 < m1 && m2 < m + 1 + 1){ - return m + 1; - } - - - if(m1 < m + 1){ - e = m; - }else{ - s = m + 1; - } - - } - - - throw new RuntimeException(); - } -} +public class Solution { + public int sqrt(int x) { + + if(x < 0) return -1; + if(x == 0) return 0; + + int s = 0; + int e = x; + + + while(s < e){ + int m = (e - s) / 2 + s; + + int m1 = x / (m + 1); + int m2 = x / (m + 1 + 1); + + if(m + 1 == m1){ + return m + 1; + } + + if(m + 1 + 1 == m2){ + return m + 1 + 1; + } + + if(m + 1 < m1 && m2 < m + 1 + 1){ + return m + 1; + } + + + if(m1 < m + 1){ + e = m; + }else{ + s = m + 1; + } + + } + + + throw new RuntimeException(); + } +} diff --git a/_includes/_root/string-to-integer-atoi/Solution.java b/_includes/_root/string-to-integer-atoi/Solution.java index 0211ce2..53baea7 100644 --- a/_includes/_root/string-to-integer-atoi/Solution.java +++ b/_includes/_root/string-to-integer-atoi/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - public int atoi(String str) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - // null "" - if (str == null || "".equals(str)) - return 0; - - char[] ds = str.toCharArray(); - - int sum = 0; - - int sign = 1; - - int s = 0; - - boolean signseen = false; - - while(s < ds.length && !('0' <= ds[s] && ds[s] <= '9')){ - - if(signseen) - return 0; - - - - if(ds[s] == '-'){ - sign *= -1; - signseen = true; - }else if(ds[s] == '+'){ - signseen = true; - }else if(ds[s] != ' '){ - return 0; - } - - s++; - } - - int e = s; - while(e < ds.length && ('0' <= ds[e] && ds[e] <= '9')){ - e++; - } - - int p = 0; - - boolean flago = false; - for(int i = s; i < e ; i++){ - - if(sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && ds[i] - '0' > Integer.MAX_VALUE % 10 )) - flago = true; - - sum = sum * 10 + (ds[i] - '0'); - } - - if (flago) - if(sign > 0) - return Integer.MAX_VALUE; - else - return Integer.MIN_VALUE; - - return sum * sign; - - } +public class Solution { + public int atoi(String str) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + // null "" + if (str == null || "".equals(str)) + return 0; + + char[] ds = str.toCharArray(); + + int sum = 0; + + int sign = 1; + + int s = 0; + + boolean signseen = false; + + while(s < ds.length && !('0' <= ds[s] && ds[s] <= '9')){ + + if(signseen) + return 0; + + + + if(ds[s] == '-'){ + sign *= -1; + signseen = true; + }else if(ds[s] == '+'){ + signseen = true; + }else if(ds[s] != ' '){ + return 0; + } + + s++; + } + + int e = s; + while(e < ds.length && ('0' <= ds[e] && ds[e] <= '9')){ + e++; + } + + int p = 0; + + boolean flago = false; + for(int i = s; i < e ; i++){ + + if(sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && ds[i] - '0' > Integer.MAX_VALUE % 10 )) + flago = true; + + sum = sum * 10 + (ds[i] - '0'); + } + + if (flago) + if(sign > 0) + return Integer.MAX_VALUE; + else + return Integer.MIN_VALUE; + + return sum * sign; + + } } \ No newline at end of file diff --git a/_includes/_root/subsets-ii/Solution.java b/_includes/_root/subsets-ii/Solution.java index 7e674b2..676423c 100644 --- a/_includes/_root/subsets-ii/Solution.java +++ b/_includes/_root/subsets-ii/Solution.java @@ -1,49 +1,49 @@ -public class Solution { - public List> subsetsWithDup(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if (num.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(num); - - long mask = (long) Math.pow(2, num.length); - - next: - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < num.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(num[(int)j]); - } - } - - next_lv: - for(List _level : rt){ - - if(_level.size() == level.size()){ - for(int li = 0; li < _level.size(); li++){ - if(!_level.get(li).equals(level.get(li))) - continue next_lv; - } - - continue next; - } - } - rt.add(level); - - } - - return rt; - - } -} +public class Solution { + public List> subsetsWithDup(int[] num) { + + ArrayList> rt = new ArrayList>(); + + if (num.length == 0){ + rt.add(new ArrayList()); + + return rt; + } + + Arrays.sort(num); + + long mask = (long) Math.pow(2, num.length); + + next: + for(long i = 0; i < mask; i++){ + + ArrayList level = new ArrayList(); + + for(long j = 0; j < num.length; j++){ + + long x = (long) Math.pow(2, j); + + if((x & i) == x){ + level.add(num[(int)j]); + } + } + + next_lv: + for(List _level : rt){ + + if(_level.size() == level.size()){ + for(int li = 0; li < _level.size(); li++){ + if(!_level.get(li).equals(level.get(li))) + continue next_lv; + } + + continue next; + } + } + rt.add(level); + + } + + return rt; + + } +} diff --git a/_includes/_root/subsets/Solution.java b/_includes/_root/subsets/Solution.java index a6e54ca..f75027a 100644 --- a/_includes/_root/subsets/Solution.java +++ b/_includes/_root/subsets/Solution.java @@ -1,34 +1,34 @@ -public class Solution { - public List> subsets(int[] S) { - ArrayList> rt = new ArrayList>(); - - if (S.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(S); - - long mask = (long) Math.pow(2, S.length); - - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < S.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(S[(int)j]); - } - } - - rt.add(level); - - } - - return rt; - } -} +public class Solution { + public List> subsets(int[] S) { + ArrayList> rt = new ArrayList>(); + + if (S.length == 0){ + rt.add(new ArrayList()); + + return rt; + } + + Arrays.sort(S); + + long mask = (long) Math.pow(2, S.length); + + for(long i = 0; i < mask; i++){ + + ArrayList level = new ArrayList(); + + for(long j = 0; j < S.length; j++){ + + long x = (long) Math.pow(2, j); + + if((x & i) == x){ + level.add(S[(int)j]); + } + } + + rt.add(level); + + } + + return rt; + } +} diff --git a/_includes/_root/substring-with-concatenation-of-all-words/Solution.java b/_includes/_root/substring-with-concatenation-of-all-words/Solution.java index 8c74730..cc4f943 100644 --- a/_includes/_root/substring-with-concatenation-of-all-words/Solution.java +++ b/_includes/_root/substring-with-concatenation-of-all-words/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - boolean checkCat(String s, HashMap lm, int wordLen){ - - while(s.length() > 0){ - String w = s.substring(0, wordLen); - - Integer v = lm.get(w); - - if(v == null) return false; - if(v == 0) return false; - - s = s.substring(wordLen); - - v--; - lm.put(w, v); - } - - - return true; - } - - public List findSubstring(String S, String[] L) { - - if(L.length == 0) return new ArrayList(); - - ArrayList rt = new ArrayList(); - - - HashMap lm = new HashMap(); - - for(String l : L){ - - Integer v = lm.get(l); - - if(v == null) v = 0; - v++; - - lm.put(l, v); - } - - - final int wordLen = L[0].length(); - - for(int i = 0; i + wordLen <= S.length(); i++){ - - if(lm.containsKey(S.substring(i, i + wordLen))){ - - if(i + wordLen * L.length > S.length()){ - break; - } - - if(checkCat(S.substring(i, i + wordLen * L.length), new HashMap(lm), wordLen)){ - rt.add(i); - } - } - } - - return rt; - } +public class Solution { + + boolean checkCat(String s, HashMap lm, int wordLen){ + + while(s.length() > 0){ + String w = s.substring(0, wordLen); + + Integer v = lm.get(w); + + if(v == null) return false; + if(v == 0) return false; + + s = s.substring(wordLen); + + v--; + lm.put(w, v); + } + + + return true; + } + + public List findSubstring(String S, String[] L) { + + if(L.length == 0) return new ArrayList(); + + ArrayList rt = new ArrayList(); + + + HashMap lm = new HashMap(); + + for(String l : L){ + + Integer v = lm.get(l); + + if(v == null) v = 0; + v++; + + lm.put(l, v); + } + + + final int wordLen = L[0].length(); + + for(int i = 0; i + wordLen <= S.length(); i++){ + + if(lm.containsKey(S.substring(i, i + wordLen))){ + + if(i + wordLen * L.length > S.length()){ + break; + } + + if(checkCat(S.substring(i, i + wordLen * L.length), new HashMap(lm), wordLen)){ + rt.add(i); + } + } + } + + return rt; + } } \ No newline at end of file diff --git a/_includes/_root/sudoku-solver/Solution.java b/_includes/_root/sudoku-solver/Solution.java index 3431bff..62e3c4f 100644 --- a/_includes/_root/sudoku-solver/Solution.java +++ b/_includes/_root/sudoku-solver/Solution.java @@ -1,117 +1,117 @@ -public class Solution { - - static final List VALID = Arrays.asList(new Character[]{ '1' , '2', '3', '4', '5', '6', '7', '8', '9'}); - - boolean _solveSudoku(char[][] board){ - int mx = board.length; - int my = board[0].length; - - int x ,y; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - - if(board[x][y] == '.'){ - int _x, _y; - HashSet val = new HashSet(VALID); - - for(_y = 0; _y < my; _y++) - val.remove(board[x][_y]); - - for(_x = 0; _x < mx; _x++) - val.remove(board[_x][y]); - - int sx = x / 3 * 3; - int sy = y / 3 * 3; - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - val.remove(board[sx + ox][sy + oy]); - } - - for(char c : val){ - board[x][y] = c; - - if(isValidSudoku(board)){ - // try next '.' - if(_solveSudoku(board)){ - return true; - } - - // try another number - } - - board[x][y] = '.'; - } - - // board[x][y] is '.' return false to fail fast - return false; - } - - - } - } - - return true; - } - - public void solveSudoku(char[][] board) { - _solveSudoku(board); - } - - boolean isValidSudoku(char[][] board) { - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } - -} +public class Solution { + + static final List VALID = Arrays.asList(new Character[]{ '1' , '2', '3', '4', '5', '6', '7', '8', '9'}); + + boolean _solveSudoku(char[][] board){ + int mx = board.length; + int my = board[0].length; + + int x ,y; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + + if(board[x][y] == '.'){ + int _x, _y; + HashSet val = new HashSet(VALID); + + for(_y = 0; _y < my; _y++) + val.remove(board[x][_y]); + + for(_x = 0; _x < mx; _x++) + val.remove(board[_x][y]); + + int sx = x / 3 * 3; + int sy = y / 3 * 3; + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + val.remove(board[sx + ox][sy + oy]); + } + + for(char c : val){ + board[x][y] = c; + + if(isValidSudoku(board)){ + // try next '.' + if(_solveSudoku(board)){ + return true; + } + + // try another number + } + + board[x][y] = '.'; + } + + // board[x][y] is '.' return false to fail fast + return false; + } + + + } + } + + return true; + } + + public void solveSudoku(char[][] board) { + _solveSudoku(board); + } + + boolean isValidSudoku(char[][] board) { + + int mx = board.length; + int my = board[0].length; + + int x, y; + + for(x = 0; x < mx; x++){ + HashSet col = new HashSet(); + for(y = 0; y < my; y++){ + char c = board[x][y]; + if(c != '.'){ + if(col.contains(c)) return false; + + col.add(c); + } + } + } + + for(y = 0; y < my; y++){ + HashSet row = new HashSet(); + for(x = 0; x < mx; x++){ + char c = board[x][y]; + if(c != '.'){ + if(row.contains(c)) return false; + + row.add(c); + } + } + } + + for(x = 0; x < mx; x += 3){ + for(y = 0; y < my; y += 3){ + + HashSet block = new HashSet(); + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + char c = board[x + ox][y + oy]; + if(c != '.'){ + if(block.contains(c)) return false; + + block.add(c); + } + } + } + } + + return true; + } + +} diff --git a/_includes/_root/sum-root-to-leaf-numbers/Solution.java b/_includes/_root/sum-root-to-leaf-numbers/Solution.java index 544717f..ce7fbfb 100644 --- a/_includes/_root/sum-root-to-leaf-numbers/Solution.java +++ b/_includes/_root/sum-root-to-leaf-numbers/Solution.java @@ -1,27 +1,27 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int sumNumbers(TreeNode root, int parentval){ - - if(root == null) return 0; - - int p = parentval * 10 + root.val; - - if(root.left == null && root.right == null) return p; - - return sumNumbers(root.left, p) + sumNumbers(root.right, p); - - } - - public int sumNumbers(TreeNode root) { - return sumNumbers(root, 0); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int sumNumbers(TreeNode root, int parentval){ + + if(root == null) return 0; + + int p = parentval * 10 + root.val; + + if(root.left == null && root.right == null) return p; + + return sumNumbers(root.left, p) + sumNumbers(root.right, p); + + } + + public int sumNumbers(TreeNode root) { + return sumNumbers(root, 0); + } +} diff --git a/_includes/_root/surrounded-regions/Solution.java b/_includes/_root/surrounded-regions/Solution.java index dd6ec02..c38a38b 100644 --- a/_includes/_root/surrounded-regions/Solution.java +++ b/_includes/_root/surrounded-regions/Solution.java @@ -1,101 +1,101 @@ -public class Solution { - - static class Point{ - int x; - int y; - - Point(int x, int y){ - this.x = x; - this.y = y; - } - } - - HashSet boarderConnected; - - String pointId(int x, int y){ - return x + "," + y; - } - - - // fuck stack - boolean connectIfNotConnected(char[][] board, int x, int y){ - - if(x < 0 || y < 0) return false; - if(x >= board.length || y >= board[0].length) return false; - - if(board[x][y] == 'X') return false; - - String id = pointId(x, y); - if(boarderConnected.contains(id)) return false; - - boarderConnected.add(id); - - return true; - } - - void connectBoarder(char[][] board, int x, int y){ - - - - //connectBoarder(board, x + 1, y); - //connectBoarder(board, x - 1, y); - //connectBoarder(board, x, y + 1); - //connectBoarder(board, x, y - 1); - - LinkedList queue = new LinkedList(); - - queue.add(new Point(x, y)); - - while(!queue.isEmpty()){ - Point p = queue.poll(); - - if(connectIfNotConnected(board, p.x, p.y)){ - - queue.add(new Point(p.x + 1, p.y)); - queue.add(new Point(p.x - 1, p.y)); - - queue.add(new Point(p.x, p.y + 1)); - queue.add(new Point(p.x, p.y - 1)); - } - - } - - } - - public void solve(char[][] board) { - - int mx = board.length; - if (mx < 3) return; - - int my = board[0].length; - if (my < 3) return; - - boarderConnected = new HashSet(); - - int x; - int y; - - for(x = 0; x < mx; x++){ - connectBoarder(board, x, 0); - connectBoarder(board, x, my - 1); - } - - for(y = 0; y < my; y++){ - connectBoarder(board, 0, y); - connectBoarder(board, mx - 1, y); - } - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if(board[x][y] == 'O'){ - if(!boarderConnected.contains(pointId(x, y))){ - board[x][y] = 'X'; - } - } - } - } - - - - } +public class Solution { + + static class Point{ + int x; + int y; + + Point(int x, int y){ + this.x = x; + this.y = y; + } + } + + HashSet boarderConnected; + + String pointId(int x, int y){ + return x + "," + y; + } + + + // fuck stack + boolean connectIfNotConnected(char[][] board, int x, int y){ + + if(x < 0 || y < 0) return false; + if(x >= board.length || y >= board[0].length) return false; + + if(board[x][y] == 'X') return false; + + String id = pointId(x, y); + if(boarderConnected.contains(id)) return false; + + boarderConnected.add(id); + + return true; + } + + void connectBoarder(char[][] board, int x, int y){ + + + + //connectBoarder(board, x + 1, y); + //connectBoarder(board, x - 1, y); + //connectBoarder(board, x, y + 1); + //connectBoarder(board, x, y - 1); + + LinkedList queue = new LinkedList(); + + queue.add(new Point(x, y)); + + while(!queue.isEmpty()){ + Point p = queue.poll(); + + if(connectIfNotConnected(board, p.x, p.y)){ + + queue.add(new Point(p.x + 1, p.y)); + queue.add(new Point(p.x - 1, p.y)); + + queue.add(new Point(p.x, p.y + 1)); + queue.add(new Point(p.x, p.y - 1)); + } + + } + + } + + public void solve(char[][] board) { + + int mx = board.length; + if (mx < 3) return; + + int my = board[0].length; + if (my < 3) return; + + boarderConnected = new HashSet(); + + int x; + int y; + + for(x = 0; x < mx; x++){ + connectBoarder(board, x, 0); + connectBoarder(board, x, my - 1); + } + + for(y = 0; y < my; y++){ + connectBoarder(board, 0, y); + connectBoarder(board, mx - 1, y); + } + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + if(board[x][y] == 'O'){ + if(!boarderConnected.contains(pointId(x, y))){ + board[x][y] = 'X'; + } + } + } + } + + + + } } \ No newline at end of file diff --git a/_includes/_root/swap-nodes-in-pairs/Solution.java b/_includes/_root/swap-nodes-in-pairs/Solution.java index 8cb96bd..3d1be6b 100644 --- a/_includes/_root/swap-nodes-in-pairs/Solution.java +++ b/_includes/_root/swap-nodes-in-pairs/Solution.java @@ -1,28 +1,28 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode swapPairs(ListNode head) { - - - if (head == null) return null; - - if (head.next == null) return head; - - ListNode newhead = head.next; - head.next = swapPairs(head.next.next); - - newhead.next = head; - - return newhead; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode swapPairs(ListNode head) { + + + if (head == null) return null; + + if (head.next == null) return head; + + ListNode newhead = head.next; + head.next = swapPairs(head.next.next); + + newhead.next = head; + + return newhead; + + } } \ No newline at end of file diff --git a/_includes/_root/symmetric-tree/Solution.java b/_includes/_root/symmetric-tree/Solution.java index 0d116e0..7c8ef60 100644 --- a/_includes/_root/symmetric-tree/Solution.java +++ b/_includes/_root/symmetric-tree/Solution.java @@ -1,75 +1,75 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeNode EMPTY = new TreeNode(0); - - TreeNode nullToEmpty(TreeNode node){ - if(node == null) return EMPTY; - - return node; - } - - - public boolean isSymmetric(TreeNode root) { - - if(root == null) return true; - - LinkedList queue = new LinkedList(); - final TreeNode END = new TreeNode(0); - - LinkedList level = new LinkedList(); - - level.add(nullToEmpty(root.left)); - level.add(nullToEmpty(root.right)); - - queue.add(END); - queue.add(nullToEmpty(root.left)); - queue.add(nullToEmpty(root.right)); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - - // check - while(!level.isEmpty()){ - TreeNode left = level.pollFirst(); - TreeNode right = level.pollLast(); - - if(left == right) continue; - - if(left == EMPTY && right != EMPTY) return false; - if(left != EMPTY && right == EMPTY) return false; - - if(left.val != right.val) return false; - - } - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node); - - if(node != EMPTY){ - queue.add(nullToEmpty(node.left)); - queue.add(nullToEmpty(node.right)); - } - } - - - } - - - return true; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static final TreeNode EMPTY = new TreeNode(0); + + TreeNode nullToEmpty(TreeNode node){ + if(node == null) return EMPTY; + + return node; + } + + + public boolean isSymmetric(TreeNode root) { + + if(root == null) return true; + + LinkedList queue = new LinkedList(); + final TreeNode END = new TreeNode(0); + + LinkedList level = new LinkedList(); + + level.add(nullToEmpty(root.left)); + level.add(nullToEmpty(root.right)); + + queue.add(END); + queue.add(nullToEmpty(root.left)); + queue.add(nullToEmpty(root.right)); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + + // check + while(!level.isEmpty()){ + TreeNode left = level.pollFirst(); + TreeNode right = level.pollLast(); + + if(left == right) continue; + + if(left == EMPTY && right != EMPTY) return false; + if(left != EMPTY && right == EMPTY) return false; + + if(left.val != right.val) return false; + + } + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node); + + if(node != EMPTY){ + queue.add(nullToEmpty(node.left)); + queue.add(nullToEmpty(node.right)); + } + } + + + } + + + return true; + } +} diff --git a/_includes/_root/text-justification/Solution.java b/_includes/_root/text-justification/Solution.java index 05dbc84..e8a5f15 100644 --- a/_includes/_root/text-justification/Solution.java +++ b/_includes/_root/text-justification/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - - String space(int len){ - char[] s = new char[len]; - Arrays.fill(s, ' '); - return new String(s); - } - - public List fullJustify(String[] words, int L) { - - ArrayList text = new ArrayList(); - - int p = 0; - int lastp = 0; - while(p < words.length){ - - if(L == 0 && "".equals(words[p])){ - text.add(""); - p++; - continue; - } - - int l = 0; - while(l < L && p < words.length){ - l += words[p++].length() + 1; - } - - if(l - 1 > L) l -= words[--p].length() + 1; - - int count = p - lastp; - int left = L - l + count; - - int add; - if(count == 1) add = left; - else if (p - 1 == words.length - 1) { add = 1; left = count - 1;} // fuck... - else add = left / ( count - 1); - - left -= add * (count - 1); - - String s = ""; - for(int i = lastp; i < p - 1; i++){ - if(left > 0){ - s += words[i] + space(add + 1); - left--; - }else{ - s += words[i] + space(add); - } - } - - left = L - s.length() - words[p - 1].length(); - - if(count == 1 || p - 1 == words.length - 1) // fuck... - s += words[p - 1] + space(left); - else - s += space(left) + words[p - 1]; - - text.add(s); - lastp = p; - } - - return text; - - } -} +public class Solution { + + String space(int len){ + char[] s = new char[len]; + Arrays.fill(s, ' '); + return new String(s); + } + + public List fullJustify(String[] words, int L) { + + ArrayList text = new ArrayList(); + + int p = 0; + int lastp = 0; + while(p < words.length){ + + if(L == 0 && "".equals(words[p])){ + text.add(""); + p++; + continue; + } + + int l = 0; + while(l < L && p < words.length){ + l += words[p++].length() + 1; + } + + if(l - 1 > L) l -= words[--p].length() + 1; + + int count = p - lastp; + int left = L - l + count; + + int add; + if(count == 1) add = left; + else if (p - 1 == words.length - 1) { add = 1; left = count - 1;} // fuck... + else add = left / ( count - 1); + + left -= add * (count - 1); + + String s = ""; + for(int i = lastp; i < p - 1; i++){ + if(left > 0){ + s += words[i] + space(add + 1); + left--; + }else{ + s += words[i] + space(add); + } + } + + left = L - s.length() - words[p - 1].length(); + + if(count == 1 || p - 1 == words.length - 1) // fuck... + s += words[p - 1] + space(left); + else + s += space(left) + words[p - 1]; + + text.add(s); + lastp = p; + } + + return text; + + } +} diff --git a/_includes/_root/trapping-rain-water/Solution.java b/_includes/_root/trapping-rain-water/Solution.java index c8ae754..1cf62dd 100644 --- a/_includes/_root/trapping-rain-water/Solution.java +++ b/_includes/_root/trapping-rain-water/Solution.java @@ -1,72 +1,72 @@ -public class Solution { - - static class Bar{ - int pos; - int height; - - Bar(int pos, int height){ - this.pos = pos; - this.height = height; - } - } - - int containWater(Deque queue){ - - Bar left = queue.peekFirst(); - Bar right = queue.peekLast(); - - int water = 0; - - if(right.height >= left.height){ - - water += Math.min(right.height, left.height) * (right.pos - left.pos - 1); - - queue.removeFirst(); // remove left - - // remove stones - while(queue.size() > 1){ - water -= queue.removeFirst().height; - } - } - - return water; - } - - int[] reverseAndToInt(Deque queue){ - int[] a = new int[queue.size()]; - int i = 0; - - while(!queue.isEmpty()){ - a[i++] = queue.removeLast().height; - - } - - return a; - } - - public int trap(int[] A) { - - if (A.length <= 2) return 0; - - Deque queue = new LinkedList(); - - int s = 0; - while(s < A.length && A[s] == 0) s++; - - if(s < A.length) - queue.add(new Bar(s, A[s])); - - int water = 0; - - for(int i = s + 1; i < A.length; i++){ - - queue.add(new Bar(i, A[i])); - - water += containWater(queue); - } - - water += trap(reverseAndToInt(queue)); - - return water; - } -} +public class Solution { + + static class Bar{ + int pos; + int height; + + Bar(int pos, int height){ + this.pos = pos; + this.height = height; + } + } + + int containWater(Deque queue){ + + Bar left = queue.peekFirst(); + Bar right = queue.peekLast(); + + int water = 0; + + if(right.height >= left.height){ + + water += Math.min(right.height, left.height) * (right.pos - left.pos - 1); + + queue.removeFirst(); // remove left + + // remove stones + while(queue.size() > 1){ + water -= queue.removeFirst().height; + } + } + + return water; + } + + int[] reverseAndToInt(Deque queue){ + int[] a = new int[queue.size()]; + int i = 0; + + while(!queue.isEmpty()){ + a[i++] = queue.removeLast().height; + + } + + return a; + } + + public int trap(int[] A) { + + if (A.length <= 2) return 0; + + Deque queue = new LinkedList(); + + int s = 0; + while(s < A.length && A[s] == 0) s++; + + if(s < A.length) + queue.add(new Bar(s, A[s])); + + int water = 0; + + for(int i = s + 1; i < A.length; i++){ + + queue.add(new Bar(i, A[i])); + + water += containWater(queue); + } + + water += trap(reverseAndToInt(queue)); + + return water; + } +} diff --git a/_includes/_root/triangle/Solution.java b/_includes/_root/triangle/Solution.java index 908927b..f9d3d4d 100644 --- a/_includes/_root/triangle/Solution.java +++ b/_includes/_root/triangle/Solution.java @@ -1,27 +1,27 @@ -public class Solution { - public int minimumTotal(List> triangle) { - - final int size = triangle.size(); - if(size == 0) return 0; - if(size == 1) return triangle.get(0).get(0); - - int[] s = new int[size]; - - int i = 0; - for(int v : triangle.get(size - 1)) s[i++] = v; - - for(i = size - 2; i >=0 ; i--){ - List step = triangle.get(i); - - // s[0] = min(s[0] + step[0], s[1] + step[0]) - - for(int j = 0; j < step.size(); j++){ - s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); - } - - s[step.size()] = Integer.MAX_VALUE; - } - - return s[0]; - } -} +public class Solution { + public int minimumTotal(List> triangle) { + + final int size = triangle.size(); + if(size == 0) return 0; + if(size == 1) return triangle.get(0).get(0); + + int[] s = new int[size]; + + int i = 0; + for(int v : triangle.get(size - 1)) s[i++] = v; + + for(i = size - 2; i >=0 ; i--){ + List step = triangle.get(i); + + // s[0] = min(s[0] + step[0], s[1] + step[0]) + + for(int j = 0; j < step.size(); j++){ + s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); + } + + s[step.size()] = Integer.MAX_VALUE; + } + + return s[0]; + } +} diff --git a/_includes/_root/two-sum/Solution.java b/_includes/_root/two-sum/Solution.java index 0f00604..00e561b 100644 --- a/_includes/_root/two-sum/Solution.java +++ b/_includes/_root/two-sum/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int[] twoSum(int[] numbers, int target) { - - HashMap m = new HashMap(); - - for(int i = 0; i < numbers.length; i++){ - m.put(target - numbers[i], i); - } - - for(int i = 0; i < numbers.length; i++){ - - Integer v = m.get(numbers[i]); - - if(v != null && v != i){ - return new int[]{i + 1, v + 1}; - } - } - - throw new RuntimeException(); - } -} +public class Solution { + public int[] twoSum(int[] numbers, int target) { + + HashMap m = new HashMap(); + + for(int i = 0; i < numbers.length; i++){ + m.put(target - numbers[i], i); + } + + for(int i = 0; i < numbers.length; i++){ + + Integer v = m.get(numbers[i]); + + if(v != null && v != i){ + return new int[]{i + 1, v + 1}; + } + } + + throw new RuntimeException(); + } +} diff --git a/_includes/_root/unique-binary-search-trees-ii/Solution.java b/_includes/_root/unique-binary-search-trees-ii/Solution.java index 2448c43..a1aa6c2 100644 --- a/_includes/_root/unique-binary-search-trees-ii/Solution.java +++ b/_includes/_root/unique-binary-search-trees-ii/Solution.java @@ -1,42 +1,42 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; left = null; right = null; } - * } - */ -public class Solution { - - ArrayList generateTrees(int[] array){ - if (array.length == 0) return new ArrayList(Collections.singletonList(null)); - - ArrayList found = new ArrayList(); - - for(int i = 0; i < array.length; i++){ - - for(TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))){ - for(TreeNode right : generateTrees(Arrays.copyOfRange(array, i + 1, array.length))){ - TreeNode root = new TreeNode(array[i]); - - root.left = left; - root.right = right; - - found.add(root); - } - } - } - - return found; - } - - public List generateTrees(int n) { - - int[] array = new int[n]; - - for(int i = 0; i < n ; i++) array[i] = i + 1; - - return generateTrees(array); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; left = null; right = null; } + * } + */ +public class Solution { + + ArrayList generateTrees(int[] array){ + if (array.length == 0) return new ArrayList(Collections.singletonList(null)); + + ArrayList found = new ArrayList(); + + for(int i = 0; i < array.length; i++){ + + for(TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))){ + for(TreeNode right : generateTrees(Arrays.copyOfRange(array, i + 1, array.length))){ + TreeNode root = new TreeNode(array[i]); + + root.left = left; + root.right = right; + + found.add(root); + } + } + } + + return found; + } + + public List generateTrees(int n) { + + int[] array = new int[n]; + + for(int i = 0; i < n ; i++) array[i] = i + 1; + + return generateTrees(array); + } +} diff --git a/_includes/_root/unique-binary-search-trees/Solution.java b/_includes/_root/unique-binary-search-trees/Solution.java index b3b11b4..bd693cc 100644 --- a/_includes/_root/unique-binary-search-trees/Solution.java +++ b/_includes/_root/unique-binary-search-trees/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public int numTrees(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(n == 0) return 1; - - int s = 0; - - for(int i = 0; i < n; i++){ - s += numTrees(i) * numTrees(n - 1 - i); - } - - return s; - } +public class Solution { + public int numTrees(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(n == 0) return 1; + + int s = 0; + + for(int i = 0; i < n; i++){ + s += numTrees(i) * numTrees(n - 1 - i); + } + + return s; + } } \ No newline at end of file diff --git a/_includes/_root/unique-paths-ii/Solution.java b/_includes/_root/unique-paths-ii/Solution.java index 221ee49..f8d2b02 100644 --- a/_includes/_root/unique-paths-ii/Solution.java +++ b/_includes/_root/unique-paths-ii/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public int uniquePathsWithObstacles(int[][] obstacleGrid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int mx = obstacleGrid.length; - int my = obstacleGrid[0].length; - - if(obstacleGrid[0][0] == 1) return 0; - if(obstacleGrid[mx - 1][my - 1] == 1) return 0; - - int x, y; - - boolean blocked = false; - for(x = 1; x < mx ; x++){ - if (obstacleGrid[x][0] == 1) blocked = true; - obstacleGrid[x][0] = blocked ? 0 : 1; - } - - blocked = false; - for(y = 1; y < my ; y++){ - if (obstacleGrid[0][y] == 1) blocked = true; - obstacleGrid[0][y] = blocked ? 0 : 1; - } - - - obstacleGrid[0][0] = 1; - - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my; y++){ - if(obstacleGrid[x][y] == 1) - obstacleGrid[x][y] = 0; - else - obstacleGrid[x][y] = obstacleGrid[x - 1][y] + obstacleGrid[x][y - 1]; - } - } - - return obstacleGrid[mx - 1][my - 1]; - - } +public class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + // Note: The Solution object is instantiated only once and is reused by each test case. + int mx = obstacleGrid.length; + int my = obstacleGrid[0].length; + + if(obstacleGrid[0][0] == 1) return 0; + if(obstacleGrid[mx - 1][my - 1] == 1) return 0; + + int x, y; + + boolean blocked = false; + for(x = 1; x < mx ; x++){ + if (obstacleGrid[x][0] == 1) blocked = true; + obstacleGrid[x][0] = blocked ? 0 : 1; + } + + blocked = false; + for(y = 1; y < my ; y++){ + if (obstacleGrid[0][y] == 1) blocked = true; + obstacleGrid[0][y] = blocked ? 0 : 1; + } + + + obstacleGrid[0][0] = 1; + + + for(x = 1; x < mx ; x++){ + for(y = 1; y < my; y++){ + if(obstacleGrid[x][y] == 1) + obstacleGrid[x][y] = 0; + else + obstacleGrid[x][y] = obstacleGrid[x - 1][y] + obstacleGrid[x][y - 1]; + } + } + + return obstacleGrid[mx - 1][my - 1]; + + } } \ No newline at end of file diff --git a/_includes/_root/unique-paths/Solution.java b/_includes/_root/unique-paths/Solution.java index 7f70ad8..d8a3e36 100644 --- a/_includes/_root/unique-paths/Solution.java +++ b/_includes/_root/unique-paths/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public int uniquePaths(int m, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(m == 0 || n == 0) return 0; - - int[][] matrix = new int[m][n]; - - int x, y; - - for(x = 0; x < m; x++) - matrix[x][0] = 1; - - for(y = 0; y < n; y++) - matrix[0][y] = 1; - - - for(x = 1; x < m; x++){ - for(y = 1; y < n; y++){ - matrix[x][y] = matrix[x - 1][y] + matrix[x][y - 1]; - } - } - - return matrix[m - 1][n - 1]; - } +public class Solution { + public int uniquePaths(int m, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(m == 0 || n == 0) return 0; + + int[][] matrix = new int[m][n]; + + int x, y; + + for(x = 0; x < m; x++) + matrix[x][0] = 1; + + for(y = 0; y < n; y++) + matrix[0][y] = 1; + + + for(x = 1; x < m; x++){ + for(y = 1; y < n; y++){ + matrix[x][y] = matrix[x - 1][y] + matrix[x][y - 1]; + } + } + + return matrix[m - 1][n - 1]; + } } \ No newline at end of file diff --git a/_includes/_root/valid-number/Solution.java b/_includes/_root/valid-number/Solution.java index 761f4c7..96337f3 100644 --- a/_includes/_root/valid-number/Solution.java +++ b/_includes/_root/valid-number/Solution.java @@ -1,44 +1,44 @@ -public class Solution { - - - public boolean isNumber(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if ( s == null) return false; - else if( s.length() == 0 ) return false; - - char[] chars = s.toCharArray(); - int st = 0 , ed = chars.length - 1; - - while((st < ed ) && chars[st] == ' ') st++; - while((st < ed ) && chars[ed] == ' ') ed--; - - if(chars[st] == ' ') return false; - - boolean dot = false; - boolean ex = false; - boolean num = false; - - for(int i = st; i <= ed; i++ ){ - char c = chars[i]; - if ('0' <= c && c <= '9'){ - num = true; - }else if ( c == 'e'){ - if(ex) return false; - if(!num) return false; - ex = true; - num = false; - dot = false; - }else if ( c == '.'){ - if(dot) return false; - if(ex) return false; - dot = true; - }else if ( c == '-' || c == '+' ){ - if(num || dot)return false; - }else - return false; - } - - return num; - - } +public class Solution { + + + public boolean isNumber(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if ( s == null) return false; + else if( s.length() == 0 ) return false; + + char[] chars = s.toCharArray(); + int st = 0 , ed = chars.length - 1; + + while((st < ed ) && chars[st] == ' ') st++; + while((st < ed ) && chars[ed] == ' ') ed--; + + if(chars[st] == ' ') return false; + + boolean dot = false; + boolean ex = false; + boolean num = false; + + for(int i = st; i <= ed; i++ ){ + char c = chars[i]; + if ('0' <= c && c <= '9'){ + num = true; + }else if ( c == 'e'){ + if(ex) return false; + if(!num) return false; + ex = true; + num = false; + dot = false; + }else if ( c == '.'){ + if(dot) return false; + if(ex) return false; + dot = true; + }else if ( c == '-' || c == '+' ){ + if(num || dot)return false; + }else + return false; + } + + return num; + + } } \ No newline at end of file diff --git a/_includes/_root/valid-palindrome/Solution.java b/_includes/_root/valid-palindrome/Solution.java index d69b5e9..416312c 100644 --- a/_includes/_root/valid-palindrome/Solution.java +++ b/_includes/_root/valid-palindrome/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - - boolean valid(char[] chars, int i){ - return !(('A' <= chars[i] && chars[i]<= 'Z') - || ('a' <= chars[i] && chars[i]<= 'z') - || ('0' <= chars[i] && chars[i]<= '9')); - } - - public boolean isPalindrome(String s) { - if(s == null) return false; - - char[] chars = s.toLowerCase().toCharArray(); - int i = 0, j = chars.length - 1; - - while(i < j){ - - // ignore space etc. - while( (i < j) && valid(chars, i)) i++; - while( (i < j) && valid(chars, j)) j--; - - if(chars[i] != chars[j]) return false; - - i++; - j--; - } - - return true; - } -} +public class Solution { + + boolean valid(char[] chars, int i){ + return !(('A' <= chars[i] && chars[i]<= 'Z') + || ('a' <= chars[i] && chars[i]<= 'z') + || ('0' <= chars[i] && chars[i]<= '9')); + } + + public boolean isPalindrome(String s) { + if(s == null) return false; + + char[] chars = s.toLowerCase().toCharArray(); + int i = 0, j = chars.length - 1; + + while(i < j){ + + // ignore space etc. + while( (i < j) && valid(chars, i)) i++; + while( (i < j) && valid(chars, j)) j--; + + if(chars[i] != chars[j]) return false; + + i++; + j--; + } + + return true; + } +} diff --git a/_includes/_root/valid-parentheses/Solution.java b/_includes/_root/valid-parentheses/Solution.java index 2e3226e..92af536 100644 --- a/_includes/_root/valid-parentheses/Solution.java +++ b/_includes/_root/valid-parentheses/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - - boolean couple(Character l, Character r){ - if(l == null) return false; - return (l == '[' && r == ']') || (l == '(' && r == ')') || (l == '{' && r == '}'); - } - - public boolean isValid(String s) { - if(s == null) return false; - - char[] chars = s.toCharArray(); - - if(chars.length == 0 || chars.length % 2 == 1) return false; - - LinkedList stack = new LinkedList(); - - for(char c: chars){ - Character peek = stack.peek(); - - if(couple(peek, c)){ - stack.pop(); - }else{ - stack.push(c); - } - } - - return stack.size() == 0; - } -} +public class Solution { + + boolean couple(Character l, Character r){ + if(l == null) return false; + return (l == '[' && r == ']') || (l == '(' && r == ')') || (l == '{' && r == '}'); + } + + public boolean isValid(String s) { + if(s == null) return false; + + char[] chars = s.toCharArray(); + + if(chars.length == 0 || chars.length % 2 == 1) return false; + + LinkedList stack = new LinkedList(); + + for(char c: chars){ + Character peek = stack.peek(); + + if(couple(peek, c)){ + stack.pop(); + }else{ + stack.push(c); + } + } + + return stack.size() == 0; + } +} diff --git a/_includes/_root/valid-sudoku/Solution.java b/_includes/_root/valid-sudoku/Solution.java index 9fb79a2..0d0a77f 100644 --- a/_includes/_root/valid-sudoku/Solution.java +++ b/_includes/_root/valid-sudoku/Solution.java @@ -1,55 +1,55 @@ -public class Solution { - public boolean isValidSudoku(char[][] board) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } +public class Solution { + public boolean isValidSudoku(char[][] board) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int mx = board.length; + int my = board[0].length; + + int x, y; + + for(x = 0; x < mx; x++){ + HashSet col = new HashSet(); + for(y = 0; y < my; y++){ + char c = board[x][y]; + if(c != '.'){ + if(col.contains(c)) return false; + + col.add(c); + } + } + } + + for(y = 0; y < my; y++){ + HashSet row = new HashSet(); + for(x = 0; x < mx; x++){ + char c = board[x][y]; + if(c != '.'){ + if(row.contains(c)) return false; + + row.add(c); + } + } + } + + for(x = 0; x < mx; x += 3){ + for(y = 0; y < my; y += 3){ + + HashSet block = new HashSet(); + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + char c = board[x + ox][y + oy]; + if(c != '.'){ + if(block.contains(c)) return false; + + block.add(c); + } + } + } + } + + return true; + } } \ No newline at end of file diff --git a/_includes/_root/validate-binary-search-tree/Solution.java b/_includes/_root/validate-binary-search-tree/Solution.java index cf9d1a6..03ab776 100644 --- a/_includes/_root/validate-binary-search-tree/Solution.java +++ b/_includes/_root/validate-binary-search-tree/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int last; - boolean failed; - - void inorder(TreeNode root){ - - if(root == null) return; - if(failed) return; - - inorder(root.left); - - if( last >= root.val) failed = true; - last = root.val; - - inorder(root.right); - - } - - public boolean isValidBST(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - last = Integer.MIN_VALUE; - failed = false; - - if(root == null) return true; - inorder(root); - return !failed; - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int last; + boolean failed; + + void inorder(TreeNode root){ + + if(root == null) return; + if(failed) return; + + inorder(root.left); + + if( last >= root.val) failed = true; + last = root.val; + + inorder(root.right); + + } + + public boolean isValidBST(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + last = Integer.MIN_VALUE; + failed = false; + + if(root == null) return true; + inorder(root); + return !failed; + } } \ No newline at end of file diff --git a/_includes/_root/wildcard-matching/Solution.java b/_includes/_root/wildcard-matching/Solution.java index b889678..62c4dd1 100644 --- a/_includes/_root/wildcard-matching/Solution.java +++ b/_includes/_root/wildcard-matching/Solution.java @@ -1,58 +1,58 @@ -public class Solution { - public boolean isMatch(String s, String p) { - - - char[] S = s.toCharArray(); - char[] P = p.toCharArray(); - - int checkpointS = -1; - int checkpointP = -1; - - int j = 0; - - for(int i = 0; i < S.length; /*void*/){ - - if(j < P.length) { - - if(S[i] == P[j] || P[j] == '?'){ - i++; - j++; - continue; - } - - if(P[j] == '*'){ - - checkpointS = i; - checkpointP = j; - - j++; - continue; - } - } - - // mismatch - - if(checkpointS >= 0){ - - checkpointS++; - - // restore - i = checkpointS; - j = checkpointP + 1; - continue; - } - - return false; - } - - while(j < P.length) { - if(P[j] == '*'){ - j++; - } else { - return false; - } - } - - return true; - } +public class Solution { + public boolean isMatch(String s, String p) { + + + char[] S = s.toCharArray(); + char[] P = p.toCharArray(); + + int checkpointS = -1; + int checkpointP = -1; + + int j = 0; + + for(int i = 0; i < S.length; /*void*/){ + + if(j < P.length) { + + if(S[i] == P[j] || P[j] == '?'){ + i++; + j++; + continue; + } + + if(P[j] == '*'){ + + checkpointS = i; + checkpointP = j; + + j++; + continue; + } + } + + // mismatch + + if(checkpointS >= 0){ + + checkpointS++; + + // restore + i = checkpointS; + j = checkpointP + 1; + continue; + } + + return false; + } + + while(j < P.length) { + if(P[j] == '*'){ + j++; + } else { + return false; + } + } + + return true; + } } \ No newline at end of file diff --git a/_includes/_root/word-break-ii/Solution.java b/_includes/_root/word-break-ii/Solution.java index 1a26393..11df5fe 100644 --- a/_includes/_root/word-break-ii/Solution.java +++ b/_includes/_root/word-break-ii/Solution.java @@ -1,67 +1,67 @@ -public class Solution { - - String join(List list){ - if(list.isEmpty()) return ""; - - StringBuilder s = new StringBuilder(list.get(0)); - - for(int i = 1; i < list.size(); i++){ - s.append(' '); - s.append(list.get(i)); - } - - return s.toString(); - } - - ArrayList[] P; - char[] S; - ArrayList rt; - - void joinAll(int offset, LinkedList parents){ - - if(P[offset].isEmpty()){ - - rt.add(join(parents)); - return; - } - - for(Integer p : P[offset]){ - - parents.push(new String(S, p, offset - p)); - - joinAll(p, parents); - - parents.pop(); - } - - } - - public List wordBreak(String s, Set dict) { - S = s.toCharArray(); - - P = new ArrayList[S.length + 1]; - P[0] = new ArrayList(); - - for(int i = 0; i < S.length; i++){ - for(int j = 0; j <= i; j++){ - String w = new String(S, j, i - j + 1); - if(P[j] != null && dict.contains(w)){ - - if(P[i + 1] == null){ - P[i + 1] = new ArrayList(); - } - - P[i + 1].add(j); - } - } - } - - rt = new ArrayList(); - - if(P[S.length] != null){ - joinAll(S.length, new LinkedList()); - } - - return rt; - } -} +public class Solution { + + String join(List list){ + if(list.isEmpty()) return ""; + + StringBuilder s = new StringBuilder(list.get(0)); + + for(int i = 1; i < list.size(); i++){ + s.append(' '); + s.append(list.get(i)); + } + + return s.toString(); + } + + ArrayList[] P; + char[] S; + ArrayList rt; + + void joinAll(int offset, LinkedList parents){ + + if(P[offset].isEmpty()){ + + rt.add(join(parents)); + return; + } + + for(Integer p : P[offset]){ + + parents.push(new String(S, p, offset - p)); + + joinAll(p, parents); + + parents.pop(); + } + + } + + public List wordBreak(String s, Set dict) { + S = s.toCharArray(); + + P = new ArrayList[S.length + 1]; + P[0] = new ArrayList(); + + for(int i = 0; i < S.length; i++){ + for(int j = 0; j <= i; j++){ + String w = new String(S, j, i - j + 1); + if(P[j] != null && dict.contains(w)){ + + if(P[i + 1] == null){ + P[i + 1] = new ArrayList(); + } + + P[i + 1].add(j); + } + } + } + + rt = new ArrayList(); + + if(P[S.length] != null){ + joinAll(S.length, new LinkedList()); + } + + return rt; + } +} diff --git a/_includes/_root/word-break/Solution.java b/_includes/_root/word-break/Solution.java index d749cf7..ddb0b2c 100644 --- a/_includes/_root/word-break/Solution.java +++ b/_includes/_root/word-break/Solution.java @@ -1,23 +1,23 @@ -public class Solution { - public boolean wordBreak(String s, Set dict) { - - char[] S = s.toCharArray(); - - boolean[] P = new boolean[S.length + 1]; - P[0] = true; - - for(int i = 0; i < S.length; i++){ - - for(int j = 0; j <= i; j++){ - if(P[j] && dict.contains(new String(S, j, i - j + 1))){ - P[i + 1] = true; - continue; - } - } - } - - return P[S.length]; - - - } +public class Solution { + public boolean wordBreak(String s, Set dict) { + + char[] S = s.toCharArray(); + + boolean[] P = new boolean[S.length + 1]; + P[0] = true; + + for(int i = 0; i < S.length; i++){ + + for(int j = 0; j <= i; j++){ + if(P[j] && dict.contains(new String(S, j, i - j + 1))){ + P[i + 1] = true; + continue; + } + } + } + + return P[S.length]; + + + } } \ No newline at end of file diff --git a/_includes/_root/word-ladder-ii/Solution.java b/_includes/_root/word-ladder-ii/Solution.java index ae2744c..9243888 100644 --- a/_includes/_root/word-ladder-ii/Solution.java +++ b/_includes/_root/word-ladder-ii/Solution.java @@ -1,136 +1,136 @@ -public class Solution { - - static class Word { - - String word; - Set next; - - boolean end; - - Word(String word){ - this.word = word; - } - } - - static class Trace { - - Word obj; - Trace prev; - - Trace(Word obj,Trace prev){ - this.obj = obj; - this.prev = prev; - } - } - - - HashMap wmap; - - void connect(Word w, Set dict){ - if(w.next != null) return; - - Set n = new HashSet(); - - char[] ws = w.word.toCharArray(); - - for(int i = 0; i < ws.length; i++){ - char t = ws[i]; - - for(char r = 'a'; r <= 'z'; r++){ - ws[i] = r; - - String d = new String(ws); - if(dict.contains(d)){ - Word c = wmap.get(d); - n.add(c); - } - } - - ws[i] = t; - } - - w.next = n; - } - - - public List> findLadders(String start, String end, Set dict) { - - - List> rt = new ArrayList>(); - - wmap = new HashMap(); - - for(String d : dict){ - Word w = new Word(d); - wmap.put(d, w); - } - - Word _end = new Word(end); - _end.end = true; - wmap.put(end, _end); - - // help to connected to end - dict.add(end); - - - final Trace SEP = new Trace(null, null); - LinkedList queue = new LinkedList(); - - queue.add(new Trace(new Word(start), null)); - queue.add(SEP); - - boolean found = false; - - HashSet vi = new HashSet(); - HashSet svi = new HashSet(); - - while(!queue.isEmpty()){ - - Trace step = queue.poll(); - - if(step == SEP) { - vi.addAll(svi); - svi.clear(); - - if (found) break; - if (!queue.isEmpty()) queue.add(SEP); - - } else { - - Word word = step.obj; - connect(word, dict); - - - if(word.end){ - - LinkedList r = new LinkedList(); - - - Trace t = step; - - while (t != null){ - r.addFirst(t.obj.word); - t = t.prev; - } - - rt.add(r); - - found = true; - - }else if(!found){ // prevent deeper level to be visited - - for (Word p : word.next) { - - if(!vi.contains(p)) { - queue.add(new Trace(p, step)); - svi.add(p); - } - } - } - } - } - - - return rt; - } -} +public class Solution { + + static class Word { + + String word; + Set next; + + boolean end; + + Word(String word){ + this.word = word; + } + } + + static class Trace { + + Word obj; + Trace prev; + + Trace(Word obj,Trace prev){ + this.obj = obj; + this.prev = prev; + } + } + + + HashMap wmap; + + void connect(Word w, Set dict){ + if(w.next != null) return; + + Set n = new HashSet(); + + char[] ws = w.word.toCharArray(); + + for(int i = 0; i < ws.length; i++){ + char t = ws[i]; + + for(char r = 'a'; r <= 'z'; r++){ + ws[i] = r; + + String d = new String(ws); + if(dict.contains(d)){ + Word c = wmap.get(d); + n.add(c); + } + } + + ws[i] = t; + } + + w.next = n; + } + + + public List> findLadders(String start, String end, Set dict) { + + + List> rt = new ArrayList>(); + + wmap = new HashMap(); + + for(String d : dict){ + Word w = new Word(d); + wmap.put(d, w); + } + + Word _end = new Word(end); + _end.end = true; + wmap.put(end, _end); + + // help to connected to end + dict.add(end); + + + final Trace SEP = new Trace(null, null); + LinkedList queue = new LinkedList(); + + queue.add(new Trace(new Word(start), null)); + queue.add(SEP); + + boolean found = false; + + HashSet vi = new HashSet(); + HashSet svi = new HashSet(); + + while(!queue.isEmpty()){ + + Trace step = queue.poll(); + + if(step == SEP) { + vi.addAll(svi); + svi.clear(); + + if (found) break; + if (!queue.isEmpty()) queue.add(SEP); + + } else { + + Word word = step.obj; + connect(word, dict); + + + if(word.end){ + + LinkedList r = new LinkedList(); + + + Trace t = step; + + while (t != null){ + r.addFirst(t.obj.word); + t = t.prev; + } + + rt.add(r); + + found = true; + + }else if(!found){ // prevent deeper level to be visited + + for (Word p : word.next) { + + if(!vi.contains(p)) { + queue.add(new Trace(p, step)); + svi.add(p); + } + } + } + } + } + + + return rt; + } +} diff --git a/_includes/_root/word-ladder/Solution.java b/_includes/_root/word-ladder/Solution.java index 070fbfb..ce069f3 100644 --- a/_includes/_root/word-ladder/Solution.java +++ b/_includes/_root/word-ladder/Solution.java @@ -1,59 +1,59 @@ -public class Solution { - - public int ladderLength(String start, String end, Set dict) { - - LinkedList queue = new LinkedList(); - final String END = new String(); - - queue.add(start); - queue.add(END); - - int level = 0; - HashSet vi = new HashSet(); - - while(!queue.isEmpty()){ - - String current = queue.poll(); - - if(current == END){ - level++; - - if(!queue.isEmpty()) queue.add(END); - }else{ - - if(end.equals(current)) - return level + 1; - - char[] word = current.toCharArray(); - - for(int i = 0; i < word.length; i++){ - - char old = word[i]; - - for(char j = 'a'; j <= 'z' ; j++){ - - if(j == old) - continue; - - word[i] = j; - - String s = new String(word); - - if(dict.contains(s) && !vi.contains(s)){ - queue.add(s); - vi.add(s); - } - - } - - word[i] = old; - } - - } - - } - - return 0; - - } -} +public class Solution { + + public int ladderLength(String start, String end, Set dict) { + + LinkedList queue = new LinkedList(); + final String END = new String(); + + queue.add(start); + queue.add(END); + + int level = 0; + HashSet vi = new HashSet(); + + while(!queue.isEmpty()){ + + String current = queue.poll(); + + if(current == END){ + level++; + + if(!queue.isEmpty()) queue.add(END); + }else{ + + if(end.equals(current)) + return level + 1; + + char[] word = current.toCharArray(); + + for(int i = 0; i < word.length; i++){ + + char old = word[i]; + + for(char j = 'a'; j <= 'z' ; j++){ + + if(j == old) + continue; + + word[i] = j; + + String s = new String(word); + + if(dict.contains(s) && !vi.contains(s)){ + queue.add(s); + vi.add(s); + } + + } + + word[i] = old; + } + + } + + } + + return 0; + + } +} diff --git a/_includes/_root/word-search/Solution.java b/_includes/_root/word-search/Solution.java index 8a5a55c..ec307f3 100644 --- a/_includes/_root/word-search/Solution.java +++ b/_includes/_root/word-search/Solution.java @@ -1,85 +1,85 @@ -public class Solution { - - class XY{ - int x; - int y; - - XY(int x, int y) { - this.x = x; - this.y = y; - } - } - - XY[] stack; - - int mx; - int my; - - boolean search(char[][] board, char[] cs, final int index){ - - if(index >= cs.length) return true; - - // final int mx = board.length, my = board[0].length; - - final int x = stack[index - 1].x, y = stack[index - 1].y; - - next: - for(XY xy : new XY[]{new XY(x - 1, y), new XY(x + 1, y), new XY(x, y - 1), new XY(x, y + 1) }){ - int _x = xy.x; - int _y = xy.y; - - for(int i = 0; i < index ; i++){ - if(stack[i].x == _x && stack[i].y == _y) - continue next; - } - - if(_x >=0 && _x < mx && _y >= 0 && _y < my){ - if(board[_x][_y] == cs[index]){ - stack[index] = new XY(_x , _y); - - if(search(board, cs, index + 1)) - return true; - } - } - - } - - return false; - } - - - public boolean exist(char[][] board, String word) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (board.length == 0) return false; - - - int x = 0, y = 0; - - mx = board.length; - my = board[0].length; - - char[] str = word.toCharArray(); - - - //if( str.length > mx * my ) return false; // fuck.. - - stack = new XY[str.length]; - - if(str.length == 0) return false; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if( board[x][y] == str[0] ){ - - stack[0] = new XY(x, y); - if(search(board, str, 1)) - return true; - } - } - } - - return false; - } +public class Solution { + + class XY{ + int x; + int y; + + XY(int x, int y) { + this.x = x; + this.y = y; + } + } + + XY[] stack; + + int mx; + int my; + + boolean search(char[][] board, char[] cs, final int index){ + + if(index >= cs.length) return true; + + // final int mx = board.length, my = board[0].length; + + final int x = stack[index - 1].x, y = stack[index - 1].y; + + next: + for(XY xy : new XY[]{new XY(x - 1, y), new XY(x + 1, y), new XY(x, y - 1), new XY(x, y + 1) }){ + int _x = xy.x; + int _y = xy.y; + + for(int i = 0; i < index ; i++){ + if(stack[i].x == _x && stack[i].y == _y) + continue next; + } + + if(_x >=0 && _x < mx && _y >= 0 && _y < my){ + if(board[_x][_y] == cs[index]){ + stack[index] = new XY(_x , _y); + + if(search(board, cs, index + 1)) + return true; + } + } + + } + + return false; + } + + + public boolean exist(char[][] board, String word) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if (board.length == 0) return false; + + + int x = 0, y = 0; + + mx = board.length; + my = board[0].length; + + char[] str = word.toCharArray(); + + + //if( str.length > mx * my ) return false; // fuck.. + + stack = new XY[str.length]; + + if(str.length == 0) return false; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + if( board[x][y] == str[0] ){ + + stack[0] = new XY(x, y); + if(search(board, str, 1)) + return true; + } + } + } + + return false; + } } \ No newline at end of file diff --git a/_includes/_root/zigzag-conversion/Solution.java b/_includes/_root/zigzag-conversion/Solution.java index 26f7078..63ef178 100644 --- a/_includes/_root/zigzag-conversion/Solution.java +++ b/_includes/_root/zigzag-conversion/Solution.java @@ -1,56 +1,56 @@ -public class Solution { - public String convert(String s, int nRows) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - //row = 4 - /* - * * * - * * * * - * * * * - * * - |r-2+1| - - col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) - */ - - if(nRows == 1) return s; - - int nCols = (nRows - 2 + 1) * (s.length() / (nRows + nRows - 2) + 1); - char[][] paper = new char[nCols][nRows]; - - //int ps = 0; - char[] str = s.toCharArray(); - - int pr = 0, pc = 0; - - boolean direction = false; // true for down false for up , start up = come from up - - - for(char c : str){ - paper[pc][pr] = c; - - if(pr == 0 || pr == nRows - 1){ - direction = !direction; - } - - if(direction){ - pr++; - }else{ - pr--; - pc++; - } - } - - String rt = ""; - for(int i = 0; i < nRows; i++){ - for(int j = 0; j < nCols; j++){ - if(paper[j][i] != 0){ - rt += paper[j][i]; - } - } - } - - return rt; - - } +public class Solution { + public String convert(String s, int nRows) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + //row = 4 + /* + * * * + * * * * + * * * * + * * + |r-2+1| + + col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) + */ + + if(nRows == 1) return s; + + int nCols = (nRows - 2 + 1) * (s.length() / (nRows + nRows - 2) + 1); + char[][] paper = new char[nCols][nRows]; + + //int ps = 0; + char[] str = s.toCharArray(); + + int pr = 0, pc = 0; + + boolean direction = false; // true for down false for up , start up = come from up + + + for(char c : str){ + paper[pc][pr] = c; + + if(pr == 0 || pr == nRows - 1){ + direction = !direction; + } + + if(direction){ + pr++; + }else{ + pr--; + pc++; + } + } + + String rt = ""; + for(int i = 0; i < nRows; i++){ + for(int j = 0; j < nCols; j++){ + if(paper[j][i] != 0){ + rt += paper[j][i]; + } + } + } + + return rt; + + } } \ No newline at end of file diff --git a/add-binary/Solution.java b/add-binary/Solution.java index d4b94b1..31c8933 100644 --- a/add-binary/Solution.java +++ b/add-binary/Solution.java @@ -1,47 +1,47 @@ -public class Solution { - - int toint(char c){ - if(c >= '0') return c - '0'; - return 0; - } - - int toint(char[] chars, int index){ - if(index < chars.length && index >=0 ) return toint(chars[index]); - return 0; - } - - public String addBinary(String a, String b) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(a == null || b == null) return null; - - char[] ca = a.toCharArray(); - char[] cb = b.toCharArray(); - - int n = Math.max(ca.length, cb.length); - - int[] s = new int[n + 1]; - - - //ca = Arrays.copyOf(ca , n); - //cb = Arrays.copyOf(cb , n); - - for(int i = 0 ; i=0; i--){ - ss = ss + s[i]; - } - - if ( s[n] == 1 ) ss = "1" + ss; - - return ss; - - } +public class Solution { + + int toint(char c){ + if(c >= '0') return c - '0'; + return 0; + } + + int toint(char[] chars, int index){ + if(index < chars.length && index >=0 ) return toint(chars[index]); + return 0; + } + + public String addBinary(String a, String b) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(a == null || b == null) return null; + + char[] ca = a.toCharArray(); + char[] cb = b.toCharArray(); + + int n = Math.max(ca.length, cb.length); + + int[] s = new int[n + 1]; + + + //ca = Arrays.copyOf(ca , n); + //cb = Arrays.copyOf(cb , n); + + for(int i = 0 ; i=0; i--){ + ss = ss + s[i]; + } + + if ( s[n] == 1 ) ss = "1" + ss; + + return ss; + + } } \ No newline at end of file diff --git a/add-two-numbers/Solution.java b/add-two-numbers/Solution.java index d8b1cbe..c66f5d7 100644 --- a/add-two-numbers/Solution.java +++ b/add-two-numbers/Solution.java @@ -1,50 +1,50 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - ListNode r = new ListNode(0); - ListNode h = r; - ListNode beforeend = r; - - while(l1 !=null && l2 != null){ - r.val += l1.val + l2.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - l1 = l1.next; - l2 = l2.next; - } - - ListNode rest; - if (l1 == null) rest = l2; else rest = l1; - - while(rest != null){ - r.val += rest.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - rest = rest.next; - } - - if(beforeend.next != null && beforeend.next.val == 0) beforeend.next = null; - - return h; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + ListNode r = new ListNode(0); + ListNode h = r; + ListNode beforeend = r; + + while(l1 !=null && l2 != null){ + r.val += l1.val + l2.val; + + r.next = new ListNode(r.val / 10); + r.val %= 10; + + beforeend = r; + r = r.next; + l1 = l1.next; + l2 = l2.next; + } + + ListNode rest; + if (l1 == null) rest = l2; else rest = l1; + + while(rest != null){ + r.val += rest.val; + + r.next = new ListNode(r.val / 10); + r.val %= 10; + + beforeend = r; + r = r.next; + rest = rest.next; + } + + if(beforeend.next != null && beforeend.next.val == 0) beforeend.next = null; + + return h; + } } \ No newline at end of file diff --git a/anagrams/Solution.java b/anagrams/Solution.java index f351a86..4bea62c 100644 --- a/anagrams/Solution.java +++ b/anagrams/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public ArrayList anagrams(String[] strs) { - ArrayList found = new ArrayList(); - - HashMap> box = new HashMap>(); - - for(String str : strs){ - char[] cstr = str.toCharArray(); - Arrays.sort(cstr); - - String key = new String(cstr); - - ArrayList c = box.get(key); - if(c == null){ - box.put(key , new ArrayList()); - } - - c = box.get(key); - c.add(str); - - } - - for(ArrayList s : box.values()){ - - if(s.size() > 1){ - found.addAll(s); - } - - } - - return found; - } +public class Solution { + public ArrayList anagrams(String[] strs) { + ArrayList found = new ArrayList(); + + HashMap> box = new HashMap>(); + + for(String str : strs){ + char[] cstr = str.toCharArray(); + Arrays.sort(cstr); + + String key = new String(cstr); + + ArrayList c = box.get(key); + if(c == null){ + box.put(key , new ArrayList()); + } + + c = box.get(key); + c.add(str); + + } + + for(ArrayList s : box.values()){ + + if(s.size() > 1){ + found.addAll(s); + } + + } + + return found; + } } \ No newline at end of file diff --git a/balanced-binary-tree/Solution.java b/balanced-binary-tree/Solution.java index 66881d4..9835271 100644 --- a/balanced-binary-tree/Solution.java +++ b/balanced-binary-tree/Solution.java @@ -1,30 +1,30 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int height(TreeNode root){ - if(root == null) - return 0; - else - return Math.max(height(root.left), height(root.right)) + 1; - } - - public boolean isBalanced(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(root == null) return true; - - return - Math.abs(height(root.left) - height(root.right)) <=1 && - isBalanced(root.left) && isBalanced(root.right); - - //return isBalanced() - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int height(TreeNode root){ + if(root == null) + return 0; + else + return Math.max(height(root.left), height(root.right)) + 1; + } + + public boolean isBalanced(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(root == null) return true; + + return + Math.abs(height(root.left) - height(root.right)) <=1 && + isBalanced(root.left) && isBalanced(root.right); + + //return isBalanced() + } } \ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-ii/Solution.java b/best-time-to-buy-and-sell-stock-ii/Solution.java index 88f9adf..d037df7 100644 --- a/best-time-to-buy-and-sell-stock-ii/Solution.java +++ b/best-time-to-buy-and-sell-stock-ii/Solution.java @@ -1,24 +1,24 @@ -public class Solution { - public int maxProfit(int[] prices) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(prices.length <= 1) return 0; - - int profit = 0; - - int hold = prices[0]; - - for(int i = 1; i < prices.length; i++){ - - - if(hold < prices[i]){ - profit += prices[i] - hold; // sell - - } - - hold = prices[i]; - } - - return profit; - } +public class Solution { + public int maxProfit(int[] prices) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(prices.length <= 1) return 0; + + int profit = 0; + + int hold = prices[0]; + + for(int i = 1; i < prices.length; i++){ + + + if(hold < prices[i]){ + profit += prices[i] - hold; // sell + + } + + hold = prices[i]; + } + + return profit; + } } \ No newline at end of file diff --git a/best-time-to-buy-and-sell-stock-iii/Solution.java b/best-time-to-buy-and-sell-stock-iii/Solution.java index c9702ba..29c2e8c 100644 --- a/best-time-to-buy-and-sell-stock-iii/Solution.java +++ b/best-time-to-buy-and-sell-stock-iii/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int maxProfit(int[] prices) { - if(prices.length < 2) return 0; - - int[] left = new int[prices.length]; - int[] right = new int[prices.length]; - - - int left_min = prices[0]; - - for(int i = 1; i < prices.length; i++){ - left_min = Math.min(left_min, prices[i]); - left[i] = Math.max(prices[i] - left_min, left[i - 1]); - } - - int right_max = prices[prices.length - 1]; - - for(int i = prices.length - 2; i >= 0; i--){ - right_max = Math.max(right_max, prices[i]); - right[i] = Math.max(right_max - prices[i], right[i + 1]); - } - - int m = 0; - - for(int i = 0; i < prices.length; i++){ - m = Math.max(m, left[i] + right[i]); - } - - return m; - - } -} +public class Solution { + public int maxProfit(int[] prices) { + if(prices.length < 2) return 0; + + int[] left = new int[prices.length]; + int[] right = new int[prices.length]; + + + int left_min = prices[0]; + + for(int i = 1; i < prices.length; i++){ + left_min = Math.min(left_min, prices[i]); + left[i] = Math.max(prices[i] - left_min, left[i - 1]); + } + + int right_max = prices[prices.length - 1]; + + for(int i = prices.length - 2; i >= 0; i--){ + right_max = Math.max(right_max, prices[i]); + right[i] = Math.max(right_max - prices[i], right[i + 1]); + } + + int m = 0; + + for(int i = 0; i < prices.length; i++){ + m = Math.max(m, left[i] + right[i]); + } + + return m; + + } +} diff --git a/best-time-to-buy-and-sell-stock/Solution.java b/best-time-to-buy-and-sell-stock/Solution.java index 6b199ea..78e581c 100644 --- a/best-time-to-buy-and-sell-stock/Solution.java +++ b/best-time-to-buy-and-sell-stock/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public int maxProfit(int[] prices) { - - int max = 0; - - int lowest = Integer.MAX_VALUE; - - for(int p : prices){ - - lowest = Math.min(lowest, p); - - max = Math.max(p - lowest, max); - } - - return max; - } -} +public class Solution { + public int maxProfit(int[] prices) { + + int max = 0; + + int lowest = Integer.MAX_VALUE; + + for(int p : prices){ + + lowest = Math.min(lowest, p); + + max = Math.max(p - lowest, max); + } + + return max; + } +} diff --git a/binary-tree-inorder-traversal/Solution.java b/binary-tree-inorder-traversal/Solution.java index f204104..9a01a4a 100644 --- a/binary-tree-inorder-traversal/Solution.java +++ b/binary-tree-inorder-traversal/Solution.java @@ -1,68 +1,68 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList inorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - rt.add(current.param.val); - - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList inorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + + rt.add(current.param.val); + + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + default: + break; + } + } + + + return rt; + } +} diff --git a/binary-tree-level-order-traversal-ii/Solution.java b/binary-tree-level-order-traversal-ii/Solution.java index 65cf4ce..de6dea7 100644 --- a/binary-tree-level-order-traversal-ii/Solution.java +++ b/binary-tree-level-order-traversal-ii/Solution.java @@ -1,46 +1,46 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrderBottom(TreeNode root) { - LinkedList> rt = new LinkedList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.push(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> levelOrderBottom(TreeNode root) { + LinkedList> rt = new LinkedList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + ArrayList level = new ArrayList(); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + rt.push(new ArrayList(level)); // copy + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node.val); + + if(node.left != null) queue.addLast(node.left); + if(node.right != null) queue.addLast(node.right); + } + } + + return rt; + } +} diff --git a/binary-tree-level-order-traversal/Solution.java b/binary-tree-level-order-traversal/Solution.java index 770d2e8..714da2d 100644 --- a/binary-tree-level-order-traversal/Solution.java +++ b/binary-tree-level-order-traversal/Solution.java @@ -1,48 +1,48 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.add(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> levelOrder(TreeNode root) { + + ArrayList> rt = new ArrayList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + ArrayList level = new ArrayList(); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + rt.add(new ArrayList(level)); // copy + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node.val); + + if(node.left != null) queue.addLast(node.left); + if(node.right != null) queue.addLast(node.right); + } + } + + return rt; + + } +} diff --git a/binary-tree-maximum-path-sum/Solution.java b/binary-tree-maximum-path-sum/Solution.java index a13e12e..fca1696 100644 --- a/binary-tree-maximum-path-sum/Solution.java +++ b/binary-tree-maximum-path-sum/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int max; - - int sum(TreeNode root){ - if(root == null) return 0; - - int left = sum(root.left); - int right = sum(root.right); - - left = Math.max(left, 0); - right = Math.max(right, 0); - - int sum = root.val + left + right; - max = Math.max(max, sum); - - return Math.max(left, right) + root.val; - } - - public int maxPathSum(TreeNode root) { - - max = Integer.MIN_VALUE; - sum(root); - - return max; - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int max; + + int sum(TreeNode root){ + if(root == null) return 0; + + int left = sum(root.left); + int right = sum(root.right); + + left = Math.max(left, 0); + right = Math.max(right, 0); + + int sum = root.val + left + right; + max = Math.max(max, sum); + + return Math.max(left, right) + root.val; + } + + public int maxPathSum(TreeNode root) { + + max = Integer.MIN_VALUE; + sum(root); + + return max; + } } \ No newline at end of file diff --git a/binary-tree-postorder-traversal/Solution.java b/binary-tree-postorder-traversal/Solution.java index f2ae0df..989a06e 100644 --- a/binary-tree-postorder-traversal/Solution.java +++ b/binary-tree-postorder-traversal/Solution.java @@ -1,69 +1,69 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList postorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - - case POST: - current.returnAddress = ReturnAddress.DONE; - - rt.add(current.param.val); - - default: - break; - } - } - - - return rt; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList postorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + + case POST: + current.returnAddress = ReturnAddress.DONE; + + rt.add(current.param.val); + + default: + break; + } + } + + + return rt; + } +} diff --git a/binary-tree-preorder-traversal/Solution.java b/binary-tree-preorder-traversal/Solution.java index a7c226d..6172150 100644 --- a/binary-tree-preorder-traversal/Solution.java +++ b/binary-tree-preorder-traversal/Solution.java @@ -1,68 +1,68 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList preorderTraversal(TreeNode root) { - - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - rt.add(current.param.val); - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + public ArrayList preorderTraversal(TreeNode root) { + + ArrayList rt = new ArrayList(); + + Deque stack = new LinkedList(); + + if(root != null) + stack.push(new StackState(root)); + + while(!stack.isEmpty()){ + + StackState current = stack.pop(); + + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + rt.add(current.param.val); + + case IN: + current.returnAddress = ReturnAddress.POST; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + continue; + } + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + continue; + } + default: + break; + } + } + + + return rt; + + } +} diff --git a/binary-tree-zigzag-level-order-traversal/Solution.java b/binary-tree-zigzag-level-order-traversal/Solution.java index be4e694..b20f5f2 100644 --- a/binary-tree-zigzag-level-order-traversal/Solution.java +++ b/binary-tree-zigzag-level-order-traversal/Solution.java @@ -1,58 +1,58 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> zigzagLevelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - boolean direction = true; // true for left -> right , false for right -> left - - Deque level = new LinkedList(); - - while(!queue.isEmpty()){ - TreeNode current = queue.poll(); - - if(current == END){ - - direction = !direction; - rt.add(new ArrayList(level)); // copy - - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - if(direction){ // true for left -> right , false for right -> left - level.addLast(current.val); - }else{ - level.addFirst(current.val); - } - - - if(current.left != null) queue.add(current.left); - if(current.right != null) queue.add(current.right); - - } - } - - return rt; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public List> zigzagLevelOrder(TreeNode root) { + + ArrayList> rt = new ArrayList>(); + + if(root == null) return rt; + + final TreeNode END = new TreeNode(0); + + Deque queue = new LinkedList(); + + queue.add(root); + queue.add(END); + + boolean direction = true; // true for left -> right , false for right -> left + + Deque level = new LinkedList(); + + while(!queue.isEmpty()){ + TreeNode current = queue.poll(); + + if(current == END){ + + direction = !direction; + rt.add(new ArrayList(level)); // copy + + level.clear(); + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + if(direction){ // true for left -> right , false for right -> left + level.addLast(current.val); + }else{ + level.addFirst(current.val); + } + + + if(current.left != null) queue.add(current.left); + if(current.right != null) queue.add(current.right); + + } + } + + return rt; + + } +} diff --git a/candy/Solution.java b/candy/Solution.java index 0a35b14..1de13ae 100644 --- a/candy/Solution.java +++ b/candy/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public int candy(int[] ratings) { - - - int[] candies = new int[ratings.length]; - - Arrays.fill(candies, 1); - - for(int i = 1; i < candies.length; i++){ - if(ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) - candies[i] = candies[i - 1] + 1; - } - - for(int i = candies.length - 2; i >= 0; i--){ - if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) - candies[i] = candies[i + 1] + 1; - } - - int s = 0; - for(int c : candies) - s += c; - - return s; - - } +public class Solution { + public int candy(int[] ratings) { + + + int[] candies = new int[ratings.length]; + + Arrays.fill(candies, 1); + + for(int i = 1; i < candies.length; i++){ + if(ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) + candies[i] = candies[i - 1] + 1; + } + + for(int i = candies.length - 2; i >= 0; i--){ + if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) + candies[i] = candies[i + 1] + 1; + } + + int s = 0; + for(int c : candies) + s += c; + + return s; + + } } \ No newline at end of file diff --git a/climbing-stairs/Solution.java b/climbing-stairs/Solution.java index 75980e3..8706e30 100644 --- a/climbing-stairs/Solution.java +++ b/climbing-stairs/Solution.java @@ -1,19 +1,19 @@ -public class Solution { - public int climbStairs(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - int[] step = new int[Math.max(n + 1, 3)]; - - - step[0] = 0; - step[1] = 1; - step[2] = 2; - - for(int i = 3; i <= n; i++){ - step[i] = step[i - 1] + step[i - 2]; - } - - return step[n]; - } +public class Solution { + public int climbStairs(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + int[] step = new int[Math.max(n + 1, 3)]; + + + step[0] = 0; + step[1] = 1; + step[2] = 2; + + for(int i = 3; i <= n; i++){ + step[i] = step[i - 1] + step[i - 2]; + } + + return step[n]; + } } \ No newline at end of file diff --git a/clone-graph/Solution.java b/clone-graph/Solution.java index bf42b80..11a8222 100644 --- a/clone-graph/Solution.java +++ b/clone-graph/Solution.java @@ -1,54 +1,54 @@ -/** - * Definition for undirected graph. - * class UndirectedGraphNode { - * int label; - * ArrayList neighbors; - * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } - * }; - */ -public class Solution { - public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { - - if(node == null) return null; - - // visit - HashMap clone = new HashMap(); - - Deque queue = new LinkedList(); - - queue.add(node); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!clone.containsKey(n)){ - clone.put(n, new UndirectedGraphNode(n.label)); - - for(UndirectedGraphNode neighbor : n.neighbors){ - queue.add(neighbor); - } - } - } - - queue.add(node); - HashSet visit = new HashSet(); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!visit.contains(n)){ - visit.add(n); - - UndirectedGraphNode c = clone.get(n); - - for(UndirectedGraphNode neighbor : n.neighbors){ - c.neighbors.add(clone.get(neighbor)); - queue.add(neighbor); - } - } - } - - return clone.get(node); - - } +/** + * Definition for undirected graph. + * class UndirectedGraphNode { + * int label; + * ArrayList neighbors; + * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } + * }; + */ +public class Solution { + public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { + + if(node == null) return null; + + // visit + HashMap clone = new HashMap(); + + Deque queue = new LinkedList(); + + queue.add(node); + + while(queue.size() > 0){ + + UndirectedGraphNode n = queue.poll(); + if(!clone.containsKey(n)){ + clone.put(n, new UndirectedGraphNode(n.label)); + + for(UndirectedGraphNode neighbor : n.neighbors){ + queue.add(neighbor); + } + } + } + + queue.add(node); + HashSet visit = new HashSet(); + + while(queue.size() > 0){ + + UndirectedGraphNode n = queue.poll(); + if(!visit.contains(n)){ + visit.add(n); + + UndirectedGraphNode c = clone.get(n); + + for(UndirectedGraphNode neighbor : n.neighbors){ + c.neighbors.add(clone.get(neighbor)); + queue.add(neighbor); + } + } + } + + return clone.get(node); + + } } \ No newline at end of file diff --git a/combination-sum-ii/Solution.java b/combination-sum-ii/Solution.java index b4409da..c3b2627 100644 --- a/combination-sum-ii/Solution.java +++ b/combination-sum-ii/Solution.java @@ -1,63 +1,63 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - HashSet block; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - String uid = found.toString(); - - if(!block.contains(uid)){ - rt.add(found); - block.add(uid); - } - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target && i <= 1; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - public List> combinationSum2(int[] num, int target) { - Arrays.sort(num); - - candidates = num; - this.target = target; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - block = new HashSet(); - - search(0, 0); - - return rt; - - } -} +public class Solution { + int target; + + int[] candidates; + + int[] stack; + + ArrayList> rt; + + HashSet block; + + void search(int sp, int cur){ + + if(cur == target){ + ArrayList found = new ArrayList(); + for(int i = 0; i < stack.length; i++){ + for(int j = 0; j < stack[i]; j++){ + found.add(candidates[i]); + } + } + + String uid = found.toString(); + + if(!block.contains(uid)){ + rt.add(found); + block.add(uid); + } + return; + + } + + if(sp >= stack.length){ + return; + } + + int toadd = candidates[sp]; + + for(int i = 0; cur + toadd * i <= target && i <= 1; i++ ){ + stack[sp] = i; + search(sp + 1, cur + toadd * i); + stack[sp] = 0; + } + + } + + public List> combinationSum2(int[] num, int target) { + Arrays.sort(num); + + candidates = num; + this.target = target; + + stack = new int[candidates.length]; + + rt = new ArrayList>(); + + block = new HashSet(); + + search(0, 0); + + return rt; + + } +} diff --git a/combination-sum/Solution.java b/combination-sum/Solution.java index b93dc1f..7bb1278 100644 --- a/combination-sum/Solution.java +++ b/combination-sum/Solution.java @@ -1,56 +1,56 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - rt.add(found); - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - - public List> combinationSum(int[] candidates, int target) { - Arrays.sort(candidates); - - this.target = target; - - this.candidates = candidates; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - search(0, 0); - - return rt; - - } -} +public class Solution { + int target; + + int[] candidates; + + int[] stack; + + ArrayList> rt; + + void search(int sp, int cur){ + + if(cur == target){ + ArrayList found = new ArrayList(); + for(int i = 0; i < stack.length; i++){ + for(int j = 0; j < stack[i]; j++){ + found.add(candidates[i]); + } + } + + rt.add(found); + return; + + } + + if(sp >= stack.length){ + return; + } + + int toadd = candidates[sp]; + + for(int i = 0; cur + toadd * i <= target; i++ ){ + stack[sp] = i; + search(sp + 1, cur + toadd * i); + stack[sp] = 0; + } + + } + + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + + this.target = target; + + this.candidates = candidates; + + stack = new int[candidates.length]; + + rt = new ArrayList>(); + + search(0, 0); + + return rt; + + } +} diff --git a/combinations/Solution.java b/combinations/Solution.java index d4e83cc..83fdc3c 100644 --- a/combinations/Solution.java +++ b/combinations/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - - Integer[] num; - Integer[] stack; - int target; - - ArrayList> found; - - - void search(int p){ - if(p == target){ - found.add(new ArrayList(Arrays.asList(stack))); - return; - } - - for(Integer n : num){ - if(p > 0 && n <= stack[p - 1]) continue; - - stack[p] = n; - search(p + 1); - } - } - - public List> combine(int n, int k) { - - target = k; - - num = new Integer[n]; - for(int i = 1; i <= n; i++) num[i - 1] = i; - - stack = new Integer[k]; - - found = new ArrayList>(); - - search(0); - - return found; - } -} +public class Solution { + + Integer[] num; + Integer[] stack; + int target; + + ArrayList> found; + + + void search(int p){ + if(p == target){ + found.add(new ArrayList(Arrays.asList(stack))); + return; + } + + for(Integer n : num){ + if(p > 0 && n <= stack[p - 1]) continue; + + stack[p] = n; + search(p + 1); + } + } + + public List> combine(int n, int k) { + + target = k; + + num = new Integer[n]; + for(int i = 1; i <= n; i++) num[i - 1] = i; + + stack = new Integer[k]; + + found = new ArrayList>(); + + search(0); + + return found; + } +} diff --git a/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java b/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java index 667fece..0bdc2db 100644 --- a/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java +++ b/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java @@ -1,40 +1,40 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int[] inorder; - int[] postorder; - int p; - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; - - TreeNode root = new TreeNode(postorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != postorder[p] ; i++); - - p--; - root.right = buildTree(i + 1, ed); - root.left = buildTree(st, i); - - return root; - } - - public TreeNode buildTree(int[] inorder, int[] postorder) { - - this.p = postorder.length - 1; - this.inorder = inorder; - this.postorder = postorder; - - return buildTree(0, inorder.length); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int[] inorder; + int[] postorder; + int p; + + TreeNode buildTree(int st, int ed){ + + if(st >= ed) return null; + + TreeNode root = new TreeNode(postorder[p]); + + int i; + for(i = st ; i< ed && inorder[i] != postorder[p] ; i++); + + p--; + root.right = buildTree(i + 1, ed); + root.left = buildTree(st, i); + + return root; + } + + public TreeNode buildTree(int[] inorder, int[] postorder) { + + this.p = postorder.length - 1; + this.inorder = inorder; + this.postorder = postorder; + + return buildTree(0, inorder.length); + } } \ No newline at end of file diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java b/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java index d807911..ead52a6 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java @@ -1,44 +1,44 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int p = 0; - int[] preorder; - int[] inorder; - - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; // - - TreeNode root = new TreeNode(preorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != preorder[p] ; i++); - - p++; - root.left = buildTree(st, i); - root.right = buildTree(i + 1, ed); - - return root; - } - - - public TreeNode buildTree(int[] preorder, int[] inorder) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - this.preorder = preorder; - this.inorder = inorder; - this.p = 0; - //if (preorder.length == 0) return null; - return buildTree(0 , inorder.length); - //return new TreeNode(preorder[p]); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int p = 0; + int[] preorder; + int[] inorder; + + + TreeNode buildTree(int st, int ed){ + + if(st >= ed) return null; // + + TreeNode root = new TreeNode(preorder[p]); + + int i; + for(i = st ; i< ed && inorder[i] != preorder[p] ; i++); + + p++; + root.left = buildTree(st, i); + root.right = buildTree(i + 1, ed); + + return root; + } + + + public TreeNode buildTree(int[] preorder, int[] inorder) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + this.preorder = preorder; + this.inorder = inorder; + this.p = 0; + //if (preorder.length == 0) return null; + return buildTree(0 , inorder.length); + //return new TreeNode(preorder[p]); + } } \ No newline at end of file diff --git a/container-with-most-water/Solution.java b/container-with-most-water/Solution.java index 6d31f32..f697152 100644 --- a/container-with-most-water/Solution.java +++ b/container-with-most-water/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int maxArea(int[] height) { - - if(height.length <= 1) return 0; - - - int st = 0; - int ed = height.length - 1; - - - int max = Integer.MIN_VALUE; - - while(st < ed){ - - int current = Math.min(height[st] , height[ed]) * (ed - st); - - if(current > max) max = current; - - if(height[st] <= height[ed]){ - st++; - }else{ - ed--; - } - - - } - - - return max; - - } +public class Solution { + public int maxArea(int[] height) { + + if(height.length <= 1) return 0; + + + int st = 0; + int ed = height.length - 1; + + + int max = Integer.MIN_VALUE; + + while(st < ed){ + + int current = Math.min(height[st] , height[ed]) * (ed - st); + + if(current > max) max = current; + + if(height[st] <= height[ed]){ + st++; + }else{ + ed--; + } + + + } + + + return max; + + } } \ No newline at end of file diff --git a/convert-sorted-array-to-binary-search-tree/Solution.java b/convert-sorted-array-to-binary-search-tree/Solution.java index eee1c66..7c899fa 100644 --- a/convert-sorted-array-to-binary-search-tree/Solution.java +++ b/convert-sorted-array-to-binary-search-tree/Solution.java @@ -1,32 +1,32 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - //TreeNode - - public TreeNode sortedArrayToBST(int[] num) { - - if(num.length == 0) - return null; - - if(num.length == 1) - return new TreeNode(num[0]); - - int mid = num.length / 2; - - TreeNode root = new TreeNode(num[mid]); - - root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); - root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, num.length)); - - return root; - - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + //TreeNode + + public TreeNode sortedArrayToBST(int[] num) { + + if(num.length == 0) + return null; + + if(num.length == 1) + return new TreeNode(num[0]); + + int mid = num.length / 2; + + TreeNode root = new TreeNode(num[mid]); + + root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); + root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, num.length)); + + return root; + + } } \ No newline at end of file diff --git a/convert-sorted-list-to-binary-search-tree/Solution.java b/convert-sorted-list-to-binary-search-tree/Solution.java index 7e5fb38..ded690f 100644 --- a/convert-sorted-list-to-binary-search-tree/Solution.java +++ b/convert-sorted-list-to-binary-search-tree/Solution.java @@ -1,53 +1,53 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; next = null; } - * } - */ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - ListNode cutatmid(ListNode head){ - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - ListNode pslow = head; - - while(fast != null && fast.next != null){ - pslow = slow; - slow = slow.next; - fast = fast.next.next; - } - - pslow.next = null; - return slow; - } - - public TreeNode sortedListToBST(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - if(head.next == null) return new TreeNode(head.val); - - ListNode mid = cutatmid(head); - - TreeNode root = new TreeNode(mid.val); - root.left = sortedListToBST(head); - root.right = sortedListToBST(mid.next); - - return root; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; next = null; } + * } + */ +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + ListNode cutatmid(ListNode head){ + if(head == null) return null; + + ListNode fast = head; + ListNode slow = head; + ListNode pslow = head; + + while(fast != null && fast.next != null){ + pslow = slow; + slow = slow.next; + fast = fast.next.next; + } + + pslow.next = null; + return slow; + } + + public TreeNode sortedListToBST(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + if(head.next == null) return new TreeNode(head.val); + + ListNode mid = cutatmid(head); + + TreeNode root = new TreeNode(mid.val); + root.left = sortedListToBST(head); + root.right = sortedListToBST(mid.next); + + return root; + } } \ No newline at end of file diff --git a/copy-list-with-random-pointer/Solution.java b/copy-list-with-random-pointer/Solution.java index 626260e..947fd8d 100644 --- a/copy-list-with-random-pointer/Solution.java +++ b/copy-list-with-random-pointer/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for singly-linked list with a random pointer. - * class RandomListNode { - * int label; - * RandomListNode next, random; - * RandomListNode(int x) { this.label = x; } - * }; - */ -public class Solution { - public RandomListNode copyRandomList(RandomListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - HashMap map = new HashMap(); - - RandomListNode iter = head; - while(iter != null){ - RandomListNode born = new RandomListNode(iter.label); - map.put(iter, born); - - iter = iter.next; - } - - iter = head; - - while(iter != null){ - RandomListNode islet = map.get(iter); - - islet.next = map.get(iter.next); - islet.random = map.get(iter.random); - - iter = iter.next; - } - - return map.get(head); - } +/** + * Definition for singly-linked list with a random pointer. + * class RandomListNode { + * int label; + * RandomListNode next, random; + * RandomListNode(int x) { this.label = x; } + * }; + */ +public class Solution { + public RandomListNode copyRandomList(RandomListNode head) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + + HashMap map = new HashMap(); + + RandomListNode iter = head; + while(iter != null){ + RandomListNode born = new RandomListNode(iter.label); + map.put(iter, born); + + iter = iter.next; + } + + iter = head; + + while(iter != null){ + RandomListNode islet = map.get(iter); + + islet.next = map.get(iter.next); + islet.random = map.get(iter.random); + + iter = iter.next; + } + + return map.get(head); + } } \ No newline at end of file diff --git a/count-and-say/Solution.java b/count-and-say/Solution.java index ac820c4..d8c902a 100644 --- a/count-and-say/Solution.java +++ b/count-and-say/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - String countAndSay(String prev){ - - char[] str = prev.toCharArray(); - - int p = 1; - int count = 1; - char last = str[0]; - - String s = ""; - - while(p < str.length){ - - if(str[p] == last){ - count++; - - }else{ - - s += "" + count + last; - - last = str[p]; - count = 1; - } - - p++; - } - - s += "" + count + last; - - return s; - } - - public String countAndSay(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - String init = "1"; - - for(int i = 0; i < n - 1; i++){ - init = countAndSay(init); - } - - return init; - - } +public class Solution { + + String countAndSay(String prev){ + + char[] str = prev.toCharArray(); + + int p = 1; + int count = 1; + char last = str[0]; + + String s = ""; + + while(p < str.length){ + + if(str[p] == last){ + count++; + + }else{ + + s += "" + count + last; + + last = str[p]; + count = 1; + } + + p++; + } + + s += "" + count + last; + + return s; + } + + public String countAndSay(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + String init = "1"; + + for(int i = 0; i < n - 1; i++){ + init = countAndSay(init); + } + + return init; + + } } \ No newline at end of file diff --git a/decode-ways/Solution.java b/decode-ways/Solution.java index 5c2657d..ea87fa8 100644 --- a/decode-ways/Solution.java +++ b/decode-ways/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - - public int numDecodings(String s) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - final char[] _s = s.toCharArray(); - final int n = _s.length; - - if (n == 0 ) return 0; - - int[] step = new int[Math.max(n + 1, 3)]; - - step[0] = 1; - - step[1] = 0; - - if(_s[0] != '0') - step[1] = 1; - - for(int i = 2; i <= n; i++){ - - step[i] = 0; - - if ( _s[i - 1] != '0' ){ - step[i] += step[i - 1]; - } - - if ( _s[i - 2] != '0' ){ - if ( (_s[i - 2] - '0') * 10 + (_s[i - 1] - '0') <= 26 ) - step[i] += step[i - 2]; - } - - } - - return step[n]; - } - +public class Solution { + + public int numDecodings(String s) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + final char[] _s = s.toCharArray(); + final int n = _s.length; + + if (n == 0 ) return 0; + + int[] step = new int[Math.max(n + 1, 3)]; + + step[0] = 1; + + step[1] = 0; + + if(_s[0] != '0') + step[1] = 1; + + for(int i = 2; i <= n; i++){ + + step[i] = 0; + + if ( _s[i - 1] != '0' ){ + step[i] += step[i - 1]; + } + + if ( _s[i - 2] != '0' ){ + if ( (_s[i - 2] - '0') * 10 + (_s[i - 1] - '0') <= 26 ) + step[i] += step[i - 2]; + } + + } + + return step[n]; + } + } \ No newline at end of file diff --git a/distinct-subsequences/Solution.java b/distinct-subsequences/Solution.java index 1edb247..54077ac 100644 --- a/distinct-subsequences/Solution.java +++ b/distinct-subsequences/Solution.java @@ -1,50 +1,50 @@ -public class Solution { - public int numDistinct(String S, String T) { - - - char[] s = S.toCharArray(); - if(s.length == 0) return 0; - - char[] t = T.toCharArray(); - if(t.length == 0) return 0; - - if(t.length > s.length) return 0; - - - int[][] P = new int[s.length][t.length]; - - - P[0][0] = s[0] == t[0] ? 1 : 0; - - for(int i = 1; i < s.length; i++){ - P[i][0] = s[i] == t[0] ? 1 + P[i - 1][0] : P[i - 1][0]; - } - - - for(int j = 1; j < t.length; j++){ - for(int i = j; i < s.length; i++){ - - if(t[j] == s[i]){ - // sum choices - - P[i][j] = P[i - 1][j] + P[i - 1][j - 1]; - - - } else { - // no choice - P[i][j] = P[i - 1][j]; - - } - - - - - } - } - - - return P[s.length - 1][t.length - 1]; - - - } +public class Solution { + public int numDistinct(String S, String T) { + + + char[] s = S.toCharArray(); + if(s.length == 0) return 0; + + char[] t = T.toCharArray(); + if(t.length == 0) return 0; + + if(t.length > s.length) return 0; + + + int[][] P = new int[s.length][t.length]; + + + P[0][0] = s[0] == t[0] ? 1 : 0; + + for(int i = 1; i < s.length; i++){ + P[i][0] = s[i] == t[0] ? 1 + P[i - 1][0] : P[i - 1][0]; + } + + + for(int j = 1; j < t.length; j++){ + for(int i = j; i < s.length; i++){ + + if(t[j] == s[i]){ + // sum choices + + P[i][j] = P[i - 1][j] + P[i - 1][j - 1]; + + + } else { + // no choice + P[i][j] = P[i - 1][j]; + + } + + + + + } + } + + + return P[s.length - 1][t.length - 1]; + + + } } \ No newline at end of file diff --git a/divide-two-integers/Solution.java b/divide-two-integers/Solution.java index a08aa5f..8ca078a 100644 --- a/divide-two-integers/Solution.java +++ b/divide-two-integers/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int divide(int dividend, int divisor) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(dividend == 0) return 0; - - if(dividend == Integer.MIN_VALUE){ - if(divisor < 0) - return 1 + divide(dividend - divisor, divisor); - else - return 0 - (1 + 0 - divide((dividend + divisor), divisor)); - } - - if(divisor == Integer.MIN_VALUE){ - return dividend == divisor ? 1 : 0; - } - - if(dividend > 0 && divisor < 0) return 0 - divide(dividend, 0 - divisor); - if(dividend < 0 && divisor > 0) return 0 - divide(0 - dividend, divisor); - if(dividend < 0 && divisor < 0) return divide(0 - dividend, 0 - divisor); - - int quotient = 0; - int a = 1; - - int r = divisor; - - while(dividend >= divisor ){ - - if(r > dividend){ - a--; - r -= divisor; - }else{ - dividend -= r; - quotient += a++; - r += divisor; - } - } - - - - return quotient; - } -} +public class Solution { + public int divide(int dividend, int divisor) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(dividend == 0) return 0; + + if(dividend == Integer.MIN_VALUE){ + if(divisor < 0) + return 1 + divide(dividend - divisor, divisor); + else + return 0 - (1 + 0 - divide((dividend + divisor), divisor)); + } + + if(divisor == Integer.MIN_VALUE){ + return dividend == divisor ? 1 : 0; + } + + if(dividend > 0 && divisor < 0) return 0 - divide(dividend, 0 - divisor); + if(dividend < 0 && divisor > 0) return 0 - divide(0 - dividend, divisor); + if(dividend < 0 && divisor < 0) return divide(0 - dividend, 0 - divisor); + + int quotient = 0; + int a = 1; + + int r = divisor; + + while(dividend >= divisor ){ + + if(r > dividend){ + a--; + r -= divisor; + }else{ + dividend -= r; + quotient += a++; + r += divisor; + } + } + + + + return quotient; + } +} diff --git a/edit-distance/Solution.java b/edit-distance/Solution.java index 08fad30..97d9d43 100644 --- a/edit-distance/Solution.java +++ b/edit-distance/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - public int minDistance(String word1, String word2) { - - // http://en.wikipedia.org/wiki/Levenshtein_distance - - char[] w1 = word1.toCharArray(); - char[] w2 = word2.toCharArray(); - - - - int[][] P = new int[w1.length + 1][w2.length + 1]; - - int i, j; - - for(i = 1; i <= w1.length; i++){ - P[i][0] = i; - } - - for(j = 1; j <= w2.length; j++){ - P[0][j] = j; - } - - for(i = 1; i <= w1.length; i++){ - for(j = 1; j <= w2.length; j++){ - - P[i][j] = Math.min(P[i - 1][j], P[i][j - 1]) + 1; - - if(w1[i - 1] == w2[j - 1]){ - P[i][j] = Math.min(P[i - 1][j - 1], P[i][j]); - }else { - P[i][j] = Math.min(P[i - 1][j - 1] + 1, P[i][j]); - } - - } - } - - return P[w1.length][w2.length]; - } +public class Solution { + public int minDistance(String word1, String word2) { + + // http://en.wikipedia.org/wiki/Levenshtein_distance + + char[] w1 = word1.toCharArray(); + char[] w2 = word2.toCharArray(); + + + + int[][] P = new int[w1.length + 1][w2.length + 1]; + + int i, j; + + for(i = 1; i <= w1.length; i++){ + P[i][0] = i; + } + + for(j = 1; j <= w2.length; j++){ + P[0][j] = j; + } + + for(i = 1; i <= w1.length; i++){ + for(j = 1; j <= w2.length; j++){ + + P[i][j] = Math.min(P[i - 1][j], P[i][j - 1]) + 1; + + if(w1[i - 1] == w2[j - 1]){ + P[i][j] = Math.min(P[i - 1][j - 1], P[i][j]); + }else { + P[i][j] = Math.min(P[i - 1][j - 1] + 1, P[i][j]); + } + + } + } + + return P[w1.length][w2.length]; + } } \ No newline at end of file diff --git a/evaluate-reverse-polish-notation/Solution.java b/evaluate-reverse-polish-notation/Solution.java index ef627ab..e148b49 100644 --- a/evaluate-reverse-polish-notation/Solution.java +++ b/evaluate-reverse-polish-notation/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - public int evalRPN(String[] tokens) { - - final Deque stack = new LinkedList(); - - for(String t : tokens){ - if("+".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 + v2); - }else if("-".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 - v2); - }else if("*".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 * v2); - }else if("/".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 / v2); - }else{ - stack.push(Integer.valueOf(t)); - } - } - - return stack.pop(); - - } -} +public class Solution { + public int evalRPN(String[] tokens) { + + final Deque stack = new LinkedList(); + + for(String t : tokens){ + if("+".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 + v2); + }else if("-".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 - v2); + }else if("*".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 * v2); + }else if("/".equals(t)){ + Integer v2 = stack.pop(); + Integer v1 = stack.pop(); + + stack.push(v1 / v2); + }else{ + stack.push(Integer.valueOf(t)); + } + } + + return stack.pop(); + + } +} diff --git a/find-minimum-in-rotated-sorted-array-ii/Solution.java b/find-minimum-in-rotated-sorted-array-ii/Solution.java index 55e2b00..a43ffe6 100644 --- a/find-minimum-in-rotated-sorted-array-ii/Solution.java +++ b/find-minimum-in-rotated-sorted-array-ii/Solution.java @@ -1,30 +1,30 @@ -public class Solution { - public int findMin(int[] num) { - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // bad case - if (num[s] == num[m] && num[m] == num[e - 1]){ - return Math.min(num[s], findMin(Arrays.copyOfRange(num, s + 1, e))); - } - - // s < m < e - if ( num[s] <= num[m] && num[m] <= num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] <= num[m] && num[m] >= num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - - } -} +public class Solution { + public int findMin(int[] num) { + if(num.length == 1) return num[0]; + if(num.length == 2) return Math.min(num[0], num[1]); + + int s = 0; + int e = num.length; + + int m = (s + e) / 2; + + // bad case + if (num[s] == num[m] && num[m] == num[e - 1]){ + return Math.min(num[s], findMin(Arrays.copyOfRange(num, s + 1, e))); + } + + // s < m < e + if ( num[s] <= num[m] && num[m] <= num[e - 1]){ + return num[s]; + } + + // s < m > e + if ( num[s] <= num[m] && num[m] >= num[e - 1]){ + return findMin(Arrays.copyOfRange(num, m, e)); + } + + // s > m < e + return findMin(Arrays.copyOfRange(num, s, m + 1)); + + } +} diff --git a/find-minimum-in-rotated-sorted-array/Solution.java b/find-minimum-in-rotated-sorted-array/Solution.java index ae8b13f..f5527b2 100644 --- a/find-minimum-in-rotated-sorted-array/Solution.java +++ b/find-minimum-in-rotated-sorted-array/Solution.java @@ -1,25 +1,25 @@ -public class Solution { - public int findMin(int[] num) { - - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // s < m < e - if ( num[s] < num[m] && num[m] < num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] < num[m] && num[m] > num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - } -} +public class Solution { + public int findMin(int[] num) { + + if(num.length == 1) return num[0]; + if(num.length == 2) return Math.min(num[0], num[1]); + + int s = 0; + int e = num.length; + + int m = (s + e) / 2; + + // s < m < e + if ( num[s] < num[m] && num[m] < num[e - 1]){ + return num[s]; + } + + // s < m > e + if ( num[s] < num[m] && num[m] > num[e - 1]){ + return findMin(Arrays.copyOfRange(num, m, e)); + } + + // s > m < e + return findMin(Arrays.copyOfRange(num, s, m + 1)); + } +} diff --git a/find-peak-element/README.md b/find-peak-element/README.md index 6df33e1..e1528e4 100644 --- a/find-peak-element/README.md +++ b/find-peak-element/README.md @@ -1,11 +1,11 @@ -## logarithmic is a sign - -`O(lg n)` is something like `binary search` or `merge sort`. - - -``` -find-peak-element = first elemen only one element - index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise -``` - - +## logarithmic is a sign + +`O(lg n)` is something like `binary search` or `merge sort`. + + +``` +find-peak-element = first elemen only one element + index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise +``` + + diff --git a/first-missing-positive/Solution.java b/first-missing-positive/Solution.java index 988f30d..e61e2dc 100644 --- a/first-missing-positive/Solution.java +++ b/first-missing-positive/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public int firstMissingPositive(int[] A) { - - final int N = A.length; - - next: - for(int i = 0; i < N; i++){ - int v = A[i]; - - if(v == i + 1) continue ; - - while(true){ - if(v <= 0 || v > N){ - continue next; - } - - int t = A[v - 1]; - - if(t == v){ - continue next; - } - - A[v - 1] = v; - v = t; - } - - } - - for(int i = 0; i < N; i++){ - int v = A[i]; - - if (v != i + 1){ - return i + 1; - } - } - - return N + 1; - - } +public class Solution { + public int firstMissingPositive(int[] A) { + + final int N = A.length; + + next: + for(int i = 0; i < N; i++){ + int v = A[i]; + + if(v == i + 1) continue ; + + while(true){ + if(v <= 0 || v > N){ + continue next; + } + + int t = A[v - 1]; + + if(t == v){ + continue next; + } + + A[v - 1] = v; + v = t; + } + + } + + for(int i = 0; i < N; i++){ + int v = A[i]; + + if (v != i + 1){ + return i + 1; + } + } + + return N + 1; + + } } \ No newline at end of file diff --git a/flatten-binary-tree-to-linked-list/Solution.java b/flatten-binary-tree-to-linked-list/Solution.java index a7a9c1f..e1e416c 100644 --- a/flatten-binary-tree-to-linked-list/Solution.java +++ b/flatten-binary-tree-to-linked-list/Solution.java @@ -1,39 +1,39 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode prev; - - void preorder(TreeNode root){ - - if(root == null) return; - - TreeNode left = root.left; - TreeNode right = root.right; - - // root - if(prev != null){ - prev.right = root; - prev.left = null; - } - - prev = root; - - preorder(left); - preorder(right); - } - - - public void flatten(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - prev = null; - preorder(root); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode prev; + + void preorder(TreeNode root){ + + if(root == null) return; + + TreeNode left = root.left; + TreeNode right = root.right; + + // root + if(prev != null){ + prev.right = root; + prev.left = null; + } + + prev = root; + + preorder(left); + preorder(right); + } + + + public void flatten(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + prev = null; + preorder(root); + } } \ No newline at end of file diff --git a/gas-station/Solution.java b/gas-station/Solution.java index c4018fe..eebcb59 100644 --- a/gas-station/Solution.java +++ b/gas-station/Solution.java @@ -1,27 +1,27 @@ -public class Solution { - public int canCompleteCircuit(int[] gas, int[] cost) { - - - int start = 0; - int from_start = 0; - - int total = 0; - - for(int i = 0; i < gas.length; i++){ - int left = gas[i] - cost[i]; - total += left; - from_start += left; - - if(from_start < 0){ - from_start = 0; - start = i + 1; // restart from next station - } - } - - if(total >= 0){ - return start; - } - - return -1; - } +public class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + + + int start = 0; + int from_start = 0; + + int total = 0; + + for(int i = 0; i < gas.length; i++){ + int left = gas[i] - cost[i]; + total += left; + from_start += left; + + if(from_start < 0){ + from_start = 0; + start = i + 1; // restart from next station + } + } + + if(total >= 0){ + return start; + } + + return -1; + } } \ No newline at end of file diff --git a/generate-parentheses/Solution.java b/generate-parentheses/Solution.java index 45c1c96..26576e1 100644 --- a/generate-parentheses/Solution.java +++ b/generate-parentheses/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public List generateParenthesis(int n) { - - if (n == 0) return new ArrayList(); - if (n == 1) return Arrays.asList(new String[]{"()"}); - - HashSet temp = new HashSet(); - - for(String s : generateParenthesis(n - 1)){ - temp.add("(" + s + ")"); - temp.add("()" + s); - temp.add(s + "()"); - } - - for(int i = 2; i < n - 1 ; i++){ - for(String s : generateParenthesis(n - i)){ - for(String ss : generateParenthesis(i)){ - - temp.add(ss + s); - temp.add(s + ss); - } - - } - } - - return new ArrayList(temp); - } -} +public class Solution { + public List generateParenthesis(int n) { + + if (n == 0) return new ArrayList(); + if (n == 1) return Arrays.asList(new String[]{"()"}); + + HashSet temp = new HashSet(); + + for(String s : generateParenthesis(n - 1)){ + temp.add("(" + s + ")"); + temp.add("()" + s); + temp.add(s + "()"); + } + + for(int i = 2; i < n - 1 ; i++){ + for(String s : generateParenthesis(n - i)){ + for(String ss : generateParenthesis(i)){ + + temp.add(ss + s); + temp.add(s + ss); + } + + } + } + + return new ArrayList(temp); + } +} diff --git a/gray-code/Solution.java b/gray-code/Solution.java index e20e672..f8f383d 100644 --- a/gray-code/Solution.java +++ b/gray-code/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public ArrayList grayCode(int n) { - - ArrayList rt = new ArrayList(); - - - for(int i = 0; i < Math.pow(2, n); i++){ - // G(N) = (B(n)/2) XOR B(n) - rt.add((i / 2) ^ i); - } - - return rt; - - } +public class Solution { + public ArrayList grayCode(int n) { + + ArrayList rt = new ArrayList(); + + + for(int i = 0; i < Math.pow(2, n); i++){ + // G(N) = (B(n)/2) XOR B(n) + rt.add((i / 2) ^ i); + } + + return rt; + + } } \ No newline at end of file diff --git a/implement-strstr/Solution.java b/implement-strstr/Solution.java index 617bbeb..b606da4 100644 --- a/implement-strstr/Solution.java +++ b/implement-strstr/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - public String strStr(String haystack, String needle) { - - if(haystack == null) return null; - if(needle == null) return null; - - char[] _haystack = haystack.toCharArray(); - char[] _needle = needle.toCharArray(); - - if(_needle.length == 0) return haystack; - if(_haystack.length < _needle.length) return null; - - - int[] P = new int[_needle.length]; - - for(int j = 2; j < _needle.length; j++){ - - int k = 0; - - if(_needle[0 + P[j - 1]] == _needle[j - 1]){ - k = P[j - 1] + 1; - } - - P[j] = k; - } - - next: - for(int i = 0; i < _haystack.length; /*void*/){ - - for(int j = 0; j < _needle.length; j++){ - - if(i + j >= _haystack.length) return null; - - if(_haystack[i + j] != _needle[j]){ - i += Math.max(1, j - P[j]); - continue next; - } - } - - return new String(_haystack, i, _haystack.length - i); - } - - return null; - } +public class Solution { + public String strStr(String haystack, String needle) { + + if(haystack == null) return null; + if(needle == null) return null; + + char[] _haystack = haystack.toCharArray(); + char[] _needle = needle.toCharArray(); + + if(_needle.length == 0) return haystack; + if(_haystack.length < _needle.length) return null; + + + int[] P = new int[_needle.length]; + + for(int j = 2; j < _needle.length; j++){ + + int k = 0; + + if(_needle[0 + P[j - 1]] == _needle[j - 1]){ + k = P[j - 1] + 1; + } + + P[j] = k; + } + + next: + for(int i = 0; i < _haystack.length; /*void*/){ + + for(int j = 0; j < _needle.length; j++){ + + if(i + j >= _haystack.length) return null; + + if(_haystack[i + j] != _needle[j]){ + i += Math.max(1, j - P[j]); + continue next; + } + } + + return new String(_haystack, i, _haystack.length - i); + } + + return null; + } } \ No newline at end of file diff --git a/insert-interval/Solution.java b/insert-interval/Solution.java index 242ddf0..f63b911 100644 --- a/insert-interval/Solution.java +++ b/insert-interval/Solution.java @@ -1,45 +1,45 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List insert(List intervals, Interval newInterval) { - - int pos = intervals.size(); - - for(int i = 0; i < intervals.size(); i++){ - if(newInterval.start <= intervals.get(i).start){ - pos = i; - break; - } - } - - intervals.add(pos, newInterval); - - - ArrayList rt = new ArrayList(); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + public List insert(List intervals, Interval newInterval) { + + int pos = intervals.size(); + + for(int i = 0; i < intervals.size(); i++){ + if(newInterval.start <= intervals.get(i).start){ + pos = i; + break; + } + } + + intervals.add(pos, newInterval); + + + ArrayList rt = new ArrayList(); + + LinkedList s = new LinkedList(intervals); + + while (s.size() > 1) { + Interval i1 = s.pop(); + Interval i2 = s.pop(); + + if (i1.end >= i2.start) { + s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); + } else { + s.push(i2); + rt.add(i1); + } + } + + rt.addAll(s); + + return rt; + } +} diff --git a/insertion-sort-list/Solution.java b/insertion-sort-list/Solution.java index 82cd1be..f604a9b 100644 --- a/insertion-sort-list/Solution.java +++ b/insertion-sort-list/Solution.java @@ -1,59 +1,59 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode insertionSortList(ListNode head) { - - if(head == null) return null; - if(head.next == null) return head; - - final ListNode _head = new ListNode(Integer.MIN_VALUE); - _head.next = head; - - head = head.next; - _head.next.next = null; - - next: - while(head != null){ - - ListNode taken = head; - head = head.next; - - - ListNode cur = _head.next; - ListNode last = _head; - - - while(cur != null){ - - if(cur.val > taken.val){ - // insert - last.next = taken; - taken.next = cur; - - continue next; - - } - - cur = cur.next; - last = last.next; - } - - last.next = taken; - taken.next = null; - - } - - - return _head.next; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode insertionSortList(ListNode head) { + + if(head == null) return null; + if(head.next == null) return head; + + final ListNode _head = new ListNode(Integer.MIN_VALUE); + _head.next = head; + + head = head.next; + _head.next.next = null; + + next: + while(head != null){ + + ListNode taken = head; + head = head.next; + + + ListNode cur = _head.next; + ListNode last = _head; + + + while(cur != null){ + + if(cur.val > taken.val){ + // insert + last.next = taken; + taken.next = cur; + + continue next; + + } + + cur = cur.next; + last = last.next; + } + + last.next = taken; + taken.next = null; + + } + + + return _head.next; + + } } \ No newline at end of file diff --git a/integer-to-roman/Solution.java b/integer-to-roman/Solution.java index 341bfc5..58dc6c6 100644 --- a/integer-to-roman/Solution.java +++ b/integer-to-roman/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - public String intToRoman(int num) { - - String buff = ""; - char last = 0; - int samecount = 0; - - while (num > 0){ - for(int i = N.length - 1; i >= 0; i--){ - if(num >= N[i]){ - num -= N[i]; - buff += C[i]; - - if(last == C[i]){ - samecount++; - }else{ - samecount = 0; - } - - - if(samecount == 3){ - int s = 5 * N[i]; - - buff = buff.substring(0, buff.length() - 4); - - if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){ - s += N[i + 1]; - buff = buff.substring(0, buff.length() - 1); - } - - - return buff + C[i] + intToRoman(s) + intToRoman(num); - } - - last = C[i]; - break; - } - } - } - - return buff; - - } +public class Solution { + + /* + http://en.wikipedia.org/wiki/Roman_numerals + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1,000 + + to avoid four characters being repeated in succession + */ + + static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; + static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; + + public String intToRoman(int num) { + + String buff = ""; + char last = 0; + int samecount = 0; + + while (num > 0){ + for(int i = N.length - 1; i >= 0; i--){ + if(num >= N[i]){ + num -= N[i]; + buff += C[i]; + + if(last == C[i]){ + samecount++; + }else{ + samecount = 0; + } + + + if(samecount == 3){ + int s = 5 * N[i]; + + buff = buff.substring(0, buff.length() - 4); + + if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){ + s += N[i + 1]; + buff = buff.substring(0, buff.length() - 1); + } + + + return buff + C[i] + intToRoman(s) + intToRoman(num); + } + + last = C[i]; + break; + } + } + } + + return buff; + + } } \ No newline at end of file diff --git a/interleaving-string/Solution.java b/interleaving-string/Solution.java index bf7bcbf..1208d2e 100644 --- a/interleaving-string/Solution.java +++ b/interleaving-string/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - - char[] S1 = s1.toCharArray(); - char[] S2 = s2.toCharArray(); - char[] S3 = s3.toCharArray(); - - if(S1.length + S2.length != S3.length) return false; - - int i; - int j; - - boolean[][] map = new boolean[S1.length + 1][S2.length + 1]; - // i -> s1, j -> s2 - - map[0][0] = true; - - for(i = 1; i <= S1.length; i++){ - map[i][0] = map[i - 1][0] && S1[i - 1] == S3[i - 1]; - } - - for(j = 1; j <= S2.length; j++){ - map[0][j] = map[0][j - 1] && S2[j - 1] == S3[j - 1]; - } - - for(i = 1; i <= S1.length; i++){ - for(j = 1; j <= S2.length; j++){ - - if(map[i - 1][j]){ - map[i][j] = S3[i + j - 1] == S1[i - 1]; - continue; - } - - if(map[i][j - 1]){ - map[i][j] = S3[i + j - 1] == S2[j - 1]; - continue; - } - - } - } - - return map[S1.length][S2.length]; - - } +public class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + + char[] S1 = s1.toCharArray(); + char[] S2 = s2.toCharArray(); + char[] S3 = s3.toCharArray(); + + if(S1.length + S2.length != S3.length) return false; + + int i; + int j; + + boolean[][] map = new boolean[S1.length + 1][S2.length + 1]; + // i -> s1, j -> s2 + + map[0][0] = true; + + for(i = 1; i <= S1.length; i++){ + map[i][0] = map[i - 1][0] && S1[i - 1] == S3[i - 1]; + } + + for(j = 1; j <= S2.length; j++){ + map[0][j] = map[0][j - 1] && S2[j - 1] == S3[j - 1]; + } + + for(i = 1; i <= S1.length; i++){ + for(j = 1; j <= S2.length; j++){ + + if(map[i - 1][j]){ + map[i][j] = S3[i + j - 1] == S1[i - 1]; + continue; + } + + if(map[i][j - 1]){ + map[i][j] = S3[i + j - 1] == S2[j - 1]; + continue; + } + + } + } + + return map[S1.length][S2.length]; + + } } \ No newline at end of file diff --git a/intersection-of-two-linked-lists/README.md b/intersection-of-two-linked-lists/README.md index 3cd5882..f5548cb 100644 --- a/intersection-of-two-linked-lists/README.md +++ b/intersection-of-two-linked-lists/README.md @@ -1,22 +1,22 @@ -## Two Lists with same length - - -``` - -A: a1 → a2 - ↘ - c1 → c2 → c3 - ↗ -B: b1 → b2 - - -``` - -Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. - -## What if the length is not the same - -Make them the same. - - * find out two lists' length - * trim the longer one and remove the `overhead` +## Two Lists with same length + + +``` + +A: a1 → a2 + ↘ + c1 → c2 → c3 + ↗ +B: b1 → b2 + + +``` + +Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. + +## What if the length is not the same + +Make them the same. + + * find out two lists' length + * trim the longer one and remove the `overhead` diff --git a/jump-game-ii/Solution.java b/jump-game-ii/Solution.java index cf6d45f..19b1101 100644 --- a/jump-game-ii/Solution.java +++ b/jump-game-ii/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int jump(int[] A) { - int count = 0; - int laststep = 0; - - for(int i = 0; i < A.length - 1; /**/){ - - int maxstep = i + A[i]; - for(int j = laststep + 1; j <= i; j++){ - maxstep = Math.max(maxstep, j + A[j]); - } - - laststep = i; - i = maxstep; - - count++; - } - - return count; - } +public class Solution { + public int jump(int[] A) { + int count = 0; + int laststep = 0; + + for(int i = 0; i < A.length - 1; /**/){ + + int maxstep = i + A[i]; + for(int j = laststep + 1; j <= i; j++){ + maxstep = Math.max(maxstep, j + A[j]); + } + + laststep = i; + i = maxstep; + + count++; + } + + return count; + } } \ No newline at end of file diff --git a/jump-game/Solution.java b/jump-game/Solution.java index a409a8e..6ed7274 100644 --- a/jump-game/Solution.java +++ b/jump-game/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - - - - public boolean canJump(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(A.length == 0) return false; - - - int maxjump = 0; - - for(int i = 0; i < A.length; i++){ - if(i <= maxjump){ - if(i + A[i] < A.length - 1){ - maxjump = Math.max(maxjump, i + A[i]); - }else{ - return true; - } - } else { - return false; - } - } - - return false; - } +public class Solution { + + + + public boolean canJump(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(A.length == 0) return false; + + + int maxjump = 0; + + for(int i = 0; i < A.length; i++){ + if(i <= maxjump){ + if(i + A[i] < A.length - 1){ + maxjump = Math.max(maxjump, i + A[i]); + }else{ + return true; + } + } else { + return false; + } + } + + return false; + } } \ No newline at end of file diff --git a/largest-rectangle-in-histogram/Solution.java b/largest-rectangle-in-histogram/Solution.java index eb9dc93..4228568 100644 --- a/largest-rectangle-in-histogram/Solution.java +++ b/largest-rectangle-in-histogram/Solution.java @@ -1,52 +1,52 @@ -public class Solution { - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } +public class Solution { + + static class Rect { + int width = 1; + int height; + + Rect(int height){ + this.height = height; + } + } + + public int largestRectangleArea(int[] height) { + + if(height.length == 0) return 0; + + height = Arrays.copyOf(height, height.length + 1); + height[height.length - 1] = 0; + + Deque stack = new LinkedList(); + + stack.push(new Rect(height[0])); + + int max = 0; + + next: + for(int i = 1; i < height.length; i++){ + int h = height[i]; + + Rect r = new Rect(h); + + int sl = 0; + while(true){ + + if(stack.isEmpty() || h > stack.peek().height){ + stack.push(r); + continue next; + } + + + Rect left = stack.pop(); + + sl += left.width; + max = Math.max(max, left.height * sl); + + r.width = 1 + sl ; // merge left into new + } + + } + + return max; + } } \ No newline at end of file diff --git a/length-of-last-word/Solution.java b/length-of-last-word/Solution.java index e82e9e6..af1a9b9 100644 --- a/length-of-last-word/Solution.java +++ b/length-of-last-word/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int lengthOfLastWord(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s == null) return 0; - - char[] chars = s.toCharArray(); - - int upper = chars.length - 1; - while(upper >=0 && chars[upper] == ' ') upper--; - - int len = 0; - for(int i = 0; i<= upper; i++){ - if(chars[i] == ' ')len = 0; - else len++; - } - - return len; - - } +public class Solution { + public int lengthOfLastWord(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(s == null) return 0; + + char[] chars = s.toCharArray(); + + int upper = chars.length - 1; + while(upper >=0 && chars[upper] == ' ') upper--; + + int len = 0; + for(int i = 0; i<= upper; i++){ + if(chars[i] == ' ')len = 0; + else len++; + } + + return len; + + } } \ No newline at end of file diff --git a/letter-combinations-of-a-phone-number/Solution.java b/letter-combinations-of-a-phone-number/Solution.java index 6760c44..b5c047b 100644 --- a/letter-combinations-of-a-phone-number/Solution.java +++ b/letter-combinations-of-a-phone-number/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - static final char[][] CHAR_MAP = { - null, // 0 - null, // 1 - new char[] { 'a', 'b', 'c'}, //2 - new char[] { 'd', 'e', 'f'}, //3 - new char[] { 'g', 'h', 'i'}, //4 - new char[] { 'j', 'k', 'l'}, //5 - new char[] { 'm', 'n', 'o'}, //6 - new char[] { 'p', 'q', 'r', 's'}, //7 - new char[] { 't', 'u', 'v'}, //8 - new char[] { 'w', 'x', 'y', 'z'}, //9 - }; - - ArrayList rt; - char[] stack; - - void find(char[] digits, int p){ - - if(p == digits.length){ - rt.add(new String(stack)); - }else{ - - int num = (int) (digits[p] - '0'); - - if(CHAR_MAP[num] != null) - for(char pc : CHAR_MAP[num]){ - stack[p] = pc; - find(digits, p + 1); - } - } - - } - - public ArrayList letterCombinations(String digits) { - - rt = new ArrayList(); - stack = new char[digits.length()]; - - find(digits.toCharArray(), 0); - - return rt; - } +public class Solution { + + static final char[][] CHAR_MAP = { + null, // 0 + null, // 1 + new char[] { 'a', 'b', 'c'}, //2 + new char[] { 'd', 'e', 'f'}, //3 + new char[] { 'g', 'h', 'i'}, //4 + new char[] { 'j', 'k', 'l'}, //5 + new char[] { 'm', 'n', 'o'}, //6 + new char[] { 'p', 'q', 'r', 's'}, //7 + new char[] { 't', 'u', 'v'}, //8 + new char[] { 'w', 'x', 'y', 'z'}, //9 + }; + + ArrayList rt; + char[] stack; + + void find(char[] digits, int p){ + + if(p == digits.length){ + rt.add(new String(stack)); + }else{ + + int num = (int) (digits[p] - '0'); + + if(CHAR_MAP[num] != null) + for(char pc : CHAR_MAP[num]){ + stack[p] = pc; + find(digits, p + 1); + } + } + + } + + public ArrayList letterCombinations(String digits) { + + rt = new ArrayList(); + stack = new char[digits.length()]; + + find(digits.toCharArray(), 0); + + return rt; + } } \ No newline at end of file diff --git a/linked-list-cycle-ii/Solution.java b/linked-list-cycle-ii/Solution.java index 892bb25..bc2e4fd 100644 --- a/linked-list-cycle-ii/Solution.java +++ b/linked-list-cycle-ii/Solution.java @@ -1,70 +1,70 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode detectCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - - boolean meet = false; - - int lenc = 0; - - while ( slow.next != null){ - - slow = slow.next; - - if(slow == null) return null; - - if(fast.next == null) return null; - - fast = fast.next.next; - - if(fast == null) return null; - - if(slow == fast) { - - if(meet) break; - - meet = true; - } - - if(meet){ - lenc++; - } - } - - if(meet){ - - slow = head; - fast = head; - for(int i = 0; i< lenc; i++){ - fast = fast.next; - } - - while(slow != fast){ - slow = slow.next; - fast = fast.next; - } - - - return slow; - - } - - return null; - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + ListNode fast = head; + ListNode slow = head; + + boolean meet = false; + + int lenc = 0; + + while ( slow.next != null){ + + slow = slow.next; + + if(slow == null) return null; + + if(fast.next == null) return null; + + fast = fast.next.next; + + if(fast == null) return null; + + if(slow == fast) { + + if(meet) break; + + meet = true; + } + + if(meet){ + lenc++; + } + } + + if(meet){ + + slow = head; + fast = head; + for(int i = 0; i< lenc; i++){ + fast = fast.next; + } + + while(slow != fast){ + slow = slow.next; + fast = fast.next; + } + + + return slow; + + } + + return null; + } } \ No newline at end of file diff --git a/linked-list-cycle/Solution.java b/linked-list-cycle/Solution.java index 1d588e1..c40f172 100644 --- a/linked-list-cycle/Solution.java +++ b/linked-list-cycle/Solution.java @@ -1,37 +1,37 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public boolean hasCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return false; - - ListNode fast = head; - ListNode slow = head; - - - while(slow.next != null){ - - if(fast.next == null) return false; - - fast = fast.next.next; - - if(fast == null) return false; - - slow = slow.next; - - if(fast == slow) return true; - } - - return false; - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return false; + + ListNode fast = head; + ListNode slow = head; + + + while(slow.next != null){ + + if(fast.next == null) return false; + + fast = fast.next.next; + + if(fast == null) return false; + + slow = slow.next; + + if(fast == slow) return true; + } + + return false; + } } \ No newline at end of file diff --git a/longest-common-prefix/Solution.java b/longest-common-prefix/Solution.java index 9765ad9..e4af631 100644 --- a/longest-common-prefix/Solution.java +++ b/longest-common-prefix/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public String longestCommonPrefix(String[] strs) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int p = 0; - - if(strs.length == 0) return ""; - if(strs.length == 1) return strs[0]; - - - here: - - while(true){ - - if( p >= strs[0].length() ) break; - - char c = strs[0].charAt(p); - - for(String str : strs){ - if(str.length() <= p || str.charAt(p) != c) break here; - } - - p++; - - } - - return strs[0].substring(0, p); - - - - } +public class Solution { + public String longestCommonPrefix(String[] strs) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + int p = 0; + + if(strs.length == 0) return ""; + if(strs.length == 1) return strs[0]; + + + here: + + while(true){ + + if( p >= strs[0].length() ) break; + + char c = strs[0].charAt(p); + + for(String str : strs){ + if(str.length() <= p || str.charAt(p) != c) break here; + } + + p++; + + } + + return strs[0].substring(0, p); + + + + } } \ No newline at end of file diff --git a/longest-consecutive-sequence/Solution.java b/longest-consecutive-sequence/Solution.java index a703801..98fc2d9 100644 --- a/longest-consecutive-sequence/Solution.java +++ b/longest-consecutive-sequence/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public int longestConsecutive(int[] num) { - - HashSet nums = new HashSet(); - - for(int n : num){ - nums.add(n); - } - - int longest = 0; - - for(final int n : num){ - - int l = 1; - - int nn = n; - - nums.remove(n); - - while(nums.contains(++nn)){ - l++; - nums.remove(nn); - } - - nn = n; - - while(nums.contains(--nn)){ - l++; - nums.remove(nn); - } - - longest = Math.max(longest, l); - } - - return longest; - - } +public class Solution { + public int longestConsecutive(int[] num) { + + HashSet nums = new HashSet(); + + for(int n : num){ + nums.add(n); + } + + int longest = 0; + + for(final int n : num){ + + int l = 1; + + int nn = n; + + nums.remove(n); + + while(nums.contains(++nn)){ + l++; + nums.remove(nn); + } + + nn = n; + + while(nums.contains(--nn)){ + l++; + nums.remove(nn); + } + + longest = Math.max(longest, l); + } + + return longest; + + } } \ No newline at end of file diff --git a/longest-palindromic-substring/Solution.java b/longest-palindromic-substring/Solution.java index 851f8c3..6184350 100644 --- a/longest-palindromic-substring/Solution.java +++ b/longest-palindromic-substring/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public String longestPalindrome(String s) { - - char[] S = s.toCharArray(); - - if(S.length == 0) return ""; - - boolean[][] P = new boolean[S.length][S.length]; - - int maxi = 0; - int maxlen = 1; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - if(S[i] == S[i + 2 - 1]){ - P[2 - 1][i] = true; - maxi = i; - maxlen = 2; - } - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - - if(P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]){ - P[len - 1][i] = true; - maxi = i; - maxlen = len; - } - } - } - - return s.substring(maxi, maxi + maxlen); - } -} +public class Solution { + public String longestPalindrome(String s) { + + char[] S = s.toCharArray(); + + if(S.length == 0) return ""; + + boolean[][] P = new boolean[S.length][S.length]; + + int maxi = 0; + int maxlen = 1; + + // len 1 + Arrays.fill(P[1 - 1], true); + + // len 2 + for(int i = 0; i < S.length - 1; i++){ + if(S[i] == S[i + 2 - 1]){ + P[2 - 1][i] = true; + maxi = i; + maxlen = 2; + } + } + + // len 3 to max + for(int len = 3; len <= S.length; len++){ + + for(int i = 0; i < S.length - (len - 1); i++){ + + if(P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]){ + P[len - 1][i] = true; + maxi = i; + maxlen = len; + } + } + } + + return s.substring(maxi, maxi + maxlen); + } +} diff --git a/longest-substring-with-at-most-two-distinct-characters/README.md b/longest-substring-with-at-most-two-distinct-characters/README.md index 7f82848..0c5f96c 100644 --- a/longest-substring-with-at-most-two-distinct-characters/README.md +++ b/longest-substring-with-at-most-two-distinct-characters/README.md @@ -1,36 +1,36 @@ -## Relative of [Minimum Window Substring](../minimum-window-substring) - -This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). - -## Loop invariant - -Assume that `S` is a `string with at most two distinct char` - -when a new char `c` comes: - * append it to `S`'s right - * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` - -``` -S = 'aabb' - -new char c = 'c' - -S = 'aabbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'abbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'bbc' - -``` - - -## Finding max - -after each loop, `S` is a `string with at most two distinct char`. but, its length changes. -what we need is to find the max length. +## Relative of [Minimum Window Substring](../minimum-window-substring) + +This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). + +## Loop invariant + +Assume that `S` is a `string with at most two distinct char` + +when a new char `c` comes: + * append it to `S`'s right + * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` + +``` +S = 'aabb' + +new char c = 'c' + +S = 'aabbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'abbc' + +S is not `string with at most two distinct char` +so remove a from S + +S = 'bbc' + +``` + + +## Finding max + +after each loop, `S` is a `string with at most two distinct char`. but, its length changes. +what we need is to find the max length. diff --git a/longest-substring-without-repeating-characters/Solution.java b/longest-substring-without-repeating-characters/Solution.java index 0e6b9ae..10a18fd 100644 --- a/longest-substring-without-repeating-characters/Solution.java +++ b/longest-substring-without-repeating-characters/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public int lengthOfLongestSubstring(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(s == null) return 0; - char[] str = s.toCharArray(); - if(str.length == 0) return 0; - - - int max = 1; - - int barrier = 0; - - for(int i = 1; i < str.length; i++){ - for(int j = i - 1; j >= barrier;j--){ - if(str[i] == str[j]){ - barrier = j + 1; - break; - } - } - - max = Math.max(max, i - barrier + 1); - } - - - return max; - - } +public class Solution { + public int lengthOfLongestSubstring(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(s == null) return 0; + char[] str = s.toCharArray(); + if(str.length == 0) return 0; + + + int max = 1; + + int barrier = 0; + + for(int i = 1; i < str.length; i++){ + for(int j = i - 1; j >= barrier;j--){ + if(str[i] == str[j]){ + barrier = j + 1; + break; + } + } + + max = Math.max(max, i - barrier + 1); + } + + + return max; + + } } \ No newline at end of file diff --git a/longest-valid-parentheses/Solution.java b/longest-valid-parentheses/Solution.java index fdb64f3..744f00d 100644 --- a/longest-valid-parentheses/Solution.java +++ b/longest-valid-parentheses/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public int longestValidParentheses(String s) { - if(s == null) return 0; - - char[] chars = s.toCharArray(); - if(chars.length <= 1) return 0; - - LinkedList stack = new LinkedList(); - - int[] count = new int[chars.length]; - int max = 0; - - for(int i = 0 ; i stack = new LinkedList(); + + int[] count = new int[chars.length]; + int max = 0; + + for(int i = 0 ; i= capacity){ - removeOneFromTail(); - size--; - } - - e = new Entry(); - - e.key = key; - e.value = value; - - addBeforeHead(e); - - int h = hash(e.key); - Entry d = data[h]; - - if(d == null){ - data[h] = e; - } else { - while(d.hashnext != null){ - d = d.hashnext; - } - - d.hashnext = e; - } - - size++; - - } +public class LRUCache { + + static class Entry { + int key; + int value; + + Entry hashnext; + + Entry linknext; + Entry linkprev; + } + + Entry[] data; + + int capacity; + int size; + + Entry head; + Entry tail; + + public LRUCache(int capacity) { + this.capacity = capacity; + data = new Entry[capacity + capacity/2 + 3]; + size = 0; + + head = new Entry(); + tail = new Entry(); + + head.linknext = tail; + tail.linkprev = head; + } + + int hash(int key){ + return key % capacity; + } + + void moveToHead(Entry e){ + + Entry before = e.linkprev; + Entry after = e.linknext; + + before.linknext = after; + after.linkprev = before; + + addBeforeHead(e); + } + + void addBeforeHead(Entry e){ + Entry chead = head.linknext; + chead.linkprev = e; + head.linknext = e; + + e.linkprev = head; + e.linknext = chead; + } + + Entry _get(int key){ + int h = hash(key); + Entry e = data[h]; + + while(e != null){ + if(e.key == key){ + moveToHead(e); + return e; + } + + e = e.hashnext; + } + + return null; + } + + public int get(int key) { + Entry e = _get(key); + + if(e == null){ + return -1; + } + + return e.value; + } + + void removeOneFromTail(){ + Entry e = tail.linkprev; + + tail.linkprev = e.linkprev; + tail.linkprev.linknext = tail; + + int h = hash(e.key); + + Entry d = data[h]; + + if(d == e || d.key == e.key){ + data[h] = e.hashnext; + return; + } + + Entry p = d; + d = d.hashnext; + + while(d != null){ + + if(d == e){ + p.hashnext = e.hashnext; + return; + } + p = d; + d = d.hashnext; + } + + } + + public void set(int key, int value) { + if(capacity == 0) return; + + Entry e = _get(key); + if(e != null){ + e.value = value; + return; + } + + if(size >= capacity){ + removeOneFromTail(); + size--; + } + + e = new Entry(); + + e.key = key; + e.value = value; + + addBeforeHead(e); + + int h = hash(e.key); + Entry d = data[h]; + + if(d == null){ + data[h] = e; + } else { + while(d.hashnext != null){ + d = d.hashnext; + } + + d.hashnext = e; + } + + size++; + + } } \ No newline at end of file diff --git a/max-points-on-a-line/Solution.java b/max-points-on-a-line/Solution.java index 8866bac..9a990e2 100644 --- a/max-points-on-a-line/Solution.java +++ b/max-points-on-a-line/Solution.java @@ -1,78 +1,78 @@ -/** - * Definition for a point. - * class Point { - * int x; - * int y; - * Point() { x = 0; y = 0; } - * Point(int a, int b) { x = a; y = b; } - * } - */ -public class Solution { - - static class Line{ - - Point p1; - Point p2; - - int pointCount; - - Line(Point p1, Point p2){ - this.p1 = p1; - this.p2 = p2; - - this.pointCount = 2; - } - - boolean on(int x, int y){ - return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x); - } - - boolean on(Point p){ - return on(p.x, p.y); - } - } - - public int maxPoints(Point[] points) { - - if(points.length < 2) return points.length; - - ArrayList lines = new ArrayList(); - - lines.add(new Line(points[0], points[1])); - - for(int i = 2; i < points.length; i++){ - boolean on = false; - for(Line line : lines){ - if(line.on(points[i])){ - line.pointCount++; - on = true; - } - } - - if(!on){ - for(int j = 0; j < i; j++){ - Line l = new Line(points[j], points[i]); - lines.add(l); - - for(int k = 0; k < i; k++){ - if(j != k && l.on(points[k])){ - l.pointCount++; - break; - } - - } - } - } - } - - - int max = Integer.MIN_VALUE; - - for(Line line : lines){ - if(line.pointCount > max) max = line.pointCount; - } - - return max; - - } +/** + * Definition for a point. + * class Point { + * int x; + * int y; + * Point() { x = 0; y = 0; } + * Point(int a, int b) { x = a; y = b; } + * } + */ +public class Solution { + + static class Line{ + + Point p1; + Point p2; + + int pointCount; + + Line(Point p1, Point p2){ + this.p1 = p1; + this.p2 = p2; + + this.pointCount = 2; + } + + boolean on(int x, int y){ + return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x); + } + + boolean on(Point p){ + return on(p.x, p.y); + } + } + + public int maxPoints(Point[] points) { + + if(points.length < 2) return points.length; + + ArrayList lines = new ArrayList(); + + lines.add(new Line(points[0], points[1])); + + for(int i = 2; i < points.length; i++){ + boolean on = false; + for(Line line : lines){ + if(line.on(points[i])){ + line.pointCount++; + on = true; + } + } + + if(!on){ + for(int j = 0; j < i; j++){ + Line l = new Line(points[j], points[i]); + lines.add(l); + + for(int k = 0; k < i; k++){ + if(j != k && l.on(points[k])){ + l.pointCount++; + break; + } + + } + } + } + } + + + int max = Integer.MIN_VALUE; + + for(Line line : lines){ + if(line.pointCount > max) max = line.pointCount; + } + + return max; + + } } \ No newline at end of file diff --git a/maximal-rectangle/Solution.java b/maximal-rectangle/Solution.java index 56aee75..68873f4 100644 --- a/maximal-rectangle/Solution.java +++ b/maximal-rectangle/Solution.java @@ -1,116 +1,116 @@ -public class Solution { - public int maximalRectangle(char[][] matrix) { - int x; - int y; - - int mx = matrix.length; - if(mx == 0) return 0; - int my = matrix[0].length; - if(my == 0) return 0; - - - int[][] _matrix = new int[mx][my]; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - - int max = 0; - - for (x = 0; x < mx; x++){ - for(y = my - 1; y > 0; y--){ - if(matrix[x][y - 1] != '0' && matrix[x][y] != '0'){ - _matrix[x][y - 1] += _matrix[x][y]; - } - } - } - - for(y = 0; y < my; y++){ - - int h[] = new int[mx]; - - for(x = 0; x < mx; x++) - h[x] = _matrix[x][y]; - - max = Math.max(max, largestRectangleArea(h)); - } - - _matrix = new int[mx][my]; - - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - for (y = 0; y < my; y++){ - for(x = mx - 1; x > 0; x--){ - if(matrix[x - 1][y] != '0' && matrix[x][y] != '0'){ - _matrix[x - 1][y] += _matrix[x][y]; - } - } - } - - for(x = 0; x < mx; x++){ - max = Math.max(max, largestRectangleArea(_matrix[x])); - } - - - return max; - } - - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } +public class Solution { + public int maximalRectangle(char[][] matrix) { + int x; + int y; + + int mx = matrix.length; + if(mx == 0) return 0; + int my = matrix[0].length; + if(my == 0) return 0; + + + int[][] _matrix = new int[mx][my]; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++) { + _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; + } + } + + + int max = 0; + + for (x = 0; x < mx; x++){ + for(y = my - 1; y > 0; y--){ + if(matrix[x][y - 1] != '0' && matrix[x][y] != '0'){ + _matrix[x][y - 1] += _matrix[x][y]; + } + } + } + + for(y = 0; y < my; y++){ + + int h[] = new int[mx]; + + for(x = 0; x < mx; x++) + h[x] = _matrix[x][y]; + + max = Math.max(max, largestRectangleArea(h)); + } + + _matrix = new int[mx][my]; + + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++) { + _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; + } + } + + for (y = 0; y < my; y++){ + for(x = mx - 1; x > 0; x--){ + if(matrix[x - 1][y] != '0' && matrix[x][y] != '0'){ + _matrix[x - 1][y] += _matrix[x][y]; + } + } + } + + for(x = 0; x < mx; x++){ + max = Math.max(max, largestRectangleArea(_matrix[x])); + } + + + return max; + } + + + static class Rect { + int width = 1; + int height; + + Rect(int height){ + this.height = height; + } + } + + public int largestRectangleArea(int[] height) { + + if(height.length == 0) return 0; + + height = Arrays.copyOf(height, height.length + 1); + height[height.length - 1] = 0; + + Deque stack = new LinkedList(); + + stack.push(new Rect(height[0])); + + int max = 0; + + next: + for(int i = 1; i < height.length; i++){ + int h = height[i]; + + Rect r = new Rect(h); + + int sl = 0; + while(true){ + + if(stack.isEmpty() || h > stack.peek().height){ + stack.push(r); + continue next; + } + + + Rect left = stack.pop(); + + sl += left.width; + max = Math.max(max, left.height * sl); + + r.width = 1 + sl ; // merge left into new + } + + } + + return max; + } } \ No newline at end of file diff --git a/maximum-depth-of-binary-tree/Solution.java b/maximum-depth-of-binary-tree/Solution.java index db6e596..df368fd 100644 --- a/maximum-depth-of-binary-tree/Solution.java +++ b/maximum-depth-of-binary-tree/Solution.java @@ -1,17 +1,17 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int maxDepth(TreeNode root) { - - if(root == null) return 0; - - return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int maxDepth(TreeNode root) { + + if(root == null) return 0; + + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; + } +} diff --git a/maximum-gap/README.md b/maximum-gap/README.md index eb7dbb2..3365673 100644 --- a/maximum-gap/README.md +++ b/maximum-gap/README.md @@ -1,32 +1,32 @@ -## `O(n)` Sort - -The problem requires `O(n)` time complexity, and it looks something like sort. -[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) -are the two well known `O(n)` sort. - -Maybe an `O(32n)` radix sort will work well. - -## Bucket sort version - -> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. -Through, this solution got accepted by leetcode, I found there is a better solution. - -the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, -the `maximum gap` must be greater than `(max - min) / (N - 1)`. - -Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, -but, this time a good news is that we do not need to sort the numbers in the buckets, -what we need is only to remember the max and min of the bucket. -The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. - -after bucketing, numbers are like - -``` -[MIN] [MIN] [MIN] -[ ] [ ] ... [ ] -[MAX] [MAX] [MAX] -``` - -The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. - -Note: the will be some emtpy buckets, skip them. +## `O(n)` Sort + +The problem requires `O(n)` time complexity, and it looks something like sort. +[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) +are the two well known `O(n)` sort. + +Maybe an `O(32n)` radix sort will work well. + +## Bucket sort version + +> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. +Through, this solution got accepted by leetcode, I found there is a better solution. + +the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, +the `maximum gap` must be greater than `(max - min) / (N - 1)`. + +Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, +but, this time a good news is that we do not need to sort the numbers in the buckets, +what we need is only to remember the max and min of the bucket. +The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. + +after bucketing, numbers are like + +``` +[MIN] [MIN] [MIN] +[ ] [ ] ... [ ] +[MAX] [MAX] [MAX] +``` + +The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. + +Note: the will be some emtpy buckets, skip them. diff --git a/maximum-subarray/Solution.java b/maximum-subarray/Solution.java index 2e0fb5d..ede5dd2 100644 --- a/maximum-subarray/Solution.java +++ b/maximum-subarray/Solution.java @@ -1,20 +1,20 @@ -public class Solution { - public int maxSubArray(int[] A) { - - int max = A[0]; - int history = A[0]; - - for(int i = 1; i < A.length; i++){ - if(history < 0){ - history = A[i]; - }else{ - history += A[i]; - } - - max = Math.max(max, history); - - } - - return max; - } -} +public class Solution { + public int maxSubArray(int[] A) { + + int max = A[0]; + int history = A[0]; + + for(int i = 1; i < A.length; i++){ + if(history < 0){ + history = A[i]; + }else{ + history += A[i]; + } + + max = Math.max(max, history); + + } + + return max; + } +} diff --git a/median-of-two-sorted-arrays/Solution.java b/median-of-two-sorted-arrays/Solution.java index 007616d..4d7a58c 100644 --- a/median-of-two-sorted-arrays/Solution.java +++ b/median-of-two-sorted-arrays/Solution.java @@ -1,80 +1,80 @@ -public class Solution { - - int safe(int[] X, int i){ - - if ( i < 0) return Integer.MIN_VALUE; - - if ( i >= X.length) return Integer.MAX_VALUE; - - return X[i]; - } - - int kth(int[] A, int[] B, int k){ - - if (A.length == 0) - return B[k]; - - if (B.length == 0) - return A[k]; - - if (k == 0) - return Math.min(A[0], B[0]); - - if (A.length == 1 && B.length == 1){ - // k must be 1 - return Math.max(A[0], B[0]); - } - - int s = 0; - int e = A.length; - - while ( s < e ){ - - int m = (s + e) / 2; - - int n = k - m; - - if ( A[m] <= safe(B, n) ) { - if (n == 0 || A[m] >= safe(B, n - 1)) { - return A[m]; - } - } - - if ( safe(B, n) <= A[m] ){ - if (m == 0 || safe(B, n) >= A[m - 1]) { - return B[n]; - } - } - - if ( A[m] < safe(B, n) ) { - s = m + 1; - } else { - e = m; - } - - } - - if (A[A.length - 1] < B[0]){ - return B[k - A.length]; - } else { - return kth(B, A, k); - } - - } - - - public double findMedianSortedArrays(int A[], int B[]) { - // median of {3, 3, 5, 9, 11} is 5 - // the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 wikipedia - - int s = A.length + B.length; - final int k = s / 2; - - if(s % 2 == 1){ - return kth(A, B, k); - }else{ - return (kth(A, B, k - 1) + kth(A, B, k)) / 2.0; - } - - } +public class Solution { + + int safe(int[] X, int i){ + + if ( i < 0) return Integer.MIN_VALUE; + + if ( i >= X.length) return Integer.MAX_VALUE; + + return X[i]; + } + + int kth(int[] A, int[] B, int k){ + + if (A.length == 0) + return B[k]; + + if (B.length == 0) + return A[k]; + + if (k == 0) + return Math.min(A[0], B[0]); + + if (A.length == 1 && B.length == 1){ + // k must be 1 + return Math.max(A[0], B[0]); + } + + int s = 0; + int e = A.length; + + while ( s < e ){ + + int m = (s + e) / 2; + + int n = k - m; + + if ( A[m] <= safe(B, n) ) { + if (n == 0 || A[m] >= safe(B, n - 1)) { + return A[m]; + } + } + + if ( safe(B, n) <= A[m] ){ + if (m == 0 || safe(B, n) >= A[m - 1]) { + return B[n]; + } + } + + if ( A[m] < safe(B, n) ) { + s = m + 1; + } else { + e = m; + } + + } + + if (A[A.length - 1] < B[0]){ + return B[k - A.length]; + } else { + return kth(B, A, k); + } + + } + + + public double findMedianSortedArrays(int A[], int B[]) { + // median of {3, 3, 5, 9, 11} is 5 + // the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 wikipedia + + int s = A.length + B.length; + final int k = s / 2; + + if(s % 2 == 1){ + return kth(A, B, k); + }else{ + return (kth(A, B, k - 1) + kth(A, B, k)) / 2.0; + } + + } } \ No newline at end of file diff --git a/merge-intervals/Solution.java b/merge-intervals/Solution.java index 3a41e09..efab953 100644 --- a/merge-intervals/Solution.java +++ b/merge-intervals/Solution.java @@ -1,39 +1,39 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List merge(List intervals) { - - ArrayList rt = new ArrayList(); - - Collections.sort(intervals, new Comparator() { - public int compare(Interval o1, Interval o2) { - return o1.start - o2.start; - } - }); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + public List merge(List intervals) { + + ArrayList rt = new ArrayList(); + + Collections.sort(intervals, new Comparator() { + public int compare(Interval o1, Interval o2) { + return o1.start - o2.start; + } + }); + + LinkedList s = new LinkedList(intervals); + + while (s.size() > 1) { + Interval i1 = s.pop(); + Interval i2 = s.pop(); + + if (i1.end >= i2.start) { + s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); + } else { + s.push(i2); + rt.add(i1); + } + } + + rt.addAll(s); + + return rt; + } +} diff --git a/merge-k-sorted-lists/Solution.java b/merge-k-sorted-lists/Solution.java index 050969d..3760de2 100644 --- a/merge-k-sorted-lists/Solution.java +++ b/merge-k-sorted-lists/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode mergeTwoLists(ListNode l1, ListNode l2) { - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - } - - public ListNode mergeKLists(List lists) { - - final int size = lists.size(); - - if(size == 0) return null; - if(size == 1) return lists.get(0); - if(size == 2) return mergeTwoLists(lists.get(0), lists.get(1)); - - return mergeTwoLists(mergeKLists(lists.subList(0, size / 2)), mergeKLists(lists.subList(size / 2, size))); - } -} +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + } + + public ListNode mergeKLists(List lists) { + + final int size = lists.size(); + + if(size == 0) return null; + if(size == 1) return lists.get(0); + if(size == 2) return mergeTwoLists(lists.get(0), lists.get(1)); + + return mergeTwoLists(mergeKLists(lists.subList(0, size / 2)), mergeKLists(lists.subList(size / 2, size))); + } +} diff --git a/merge-sorted-array/Solution.java b/merge-sorted-array/Solution.java index 2a5fa48..c937f40 100644 --- a/merge-sorted-array/Solution.java +++ b/merge-sorted-array/Solution.java @@ -1,33 +1,33 @@ -public class Solution { - public void merge(int A[], int m, int B[], int n) { - - int pa = 0; - int pb = 0; - int up = 0; - - while(pa < m + pb && pb < n){ - - int a = A[pa]; - int b = B[pb]; - - if (a < b){ - pa++; - }else{ - // shift up - for(int i = pb + m; i > pa ; i--){ - A[i] = A[i - 1]; - } - - A[pa] = b; - pa++; - pb++; - } - - } - - for( ; pb < n; pb++){ - A[pb + m] = B[pb]; - } - - } +public class Solution { + public void merge(int A[], int m, int B[], int n) { + + int pa = 0; + int pb = 0; + int up = 0; + + while(pa < m + pb && pb < n){ + + int a = A[pa]; + int b = B[pb]; + + if (a < b){ + pa++; + }else{ + // shift up + for(int i = pb + m; i > pa ; i--){ + A[i] = A[i - 1]; + } + + A[pa] = b; + pa++; + pb++; + } + + } + + for( ; pb < n; pb++){ + A[pb + m] = B[pb]; + } + + } } \ No newline at end of file diff --git a/merge-two-sorted-lists/Solution.java b/merge-two-sorted-lists/Solution.java index 37aa0bc..514d87b 100644 --- a/merge-two-sorted-lists/Solution.java +++ b/merge-two-sorted-lists/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + + + } } \ No newline at end of file diff --git a/minimum-depth-of-binary-tree/Solution.java b/minimum-depth-of-binary-tree/Solution.java index 2a97ffa..e1e9fde 100644 --- a/minimum-depth-of-binary-tree/Solution.java +++ b/minimum-depth-of-binary-tree/Solution.java @@ -1,22 +1,22 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int minDepth(TreeNode root) { - - if(root == null) return 0; - if(root.left == null && root.right == null) return 1; - - if(root.left != null && root.right == null) return minDepth(root.left) + 1; - if(root.left == null && root.right != null) return minDepth(root.right) + 1; - - return Math.min(minDepth(root.left), minDepth(root.right)) + 1; - - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public int minDepth(TreeNode root) { + + if(root == null) return 0; + if(root.left == null && root.right == null) return 1; + + if(root.left != null && root.right == null) return minDepth(root.left) + 1; + if(root.left == null && root.right != null) return minDepth(root.right) + 1; + + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; + + } +} diff --git a/minimum-path-sum/Solution.java b/minimum-path-sum/Solution.java index e4f9e8a..129901d 100644 --- a/minimum-path-sum/Solution.java +++ b/minimum-path-sum/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public int minPathSum(int[][] grid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - - int mx = grid.length; - if(mx == 0) return 0; - - int my = grid[0].length; - - for(int x = 1; x < mx ; x++){ - grid[x][0] += grid[x - 1][0]; - } - - for(int y = 1; y < my ; y++){ - grid[0][y] += grid[0][y - 1]; - } - - for(int x = 1; x < mx; x++){ - for(int y = 1; y < my; y++){ - grid[x][y] += Math.min(grid[x - 1][y], grid[x][y - 1]); - } - } - - return grid[mx - 1][my - 1]; - } +public class Solution { + public int minPathSum(int[][] grid) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + + int mx = grid.length; + if(mx == 0) return 0; + + int my = grid[0].length; + + for(int x = 1; x < mx ; x++){ + grid[x][0] += grid[x - 1][0]; + } + + for(int y = 1; y < my ; y++){ + grid[0][y] += grid[0][y - 1]; + } + + for(int x = 1; x < mx; x++){ + for(int y = 1; y < my; y++){ + grid[x][y] += Math.min(grid[x - 1][y], grid[x][y - 1]); + } + } + + return grid[mx - 1][my - 1]; + } } \ No newline at end of file diff --git a/minimum-window-substring/Solution.java b/minimum-window-substring/Solution.java index 493407f..bf5ad7b 100644 --- a/minimum-window-substring/Solution.java +++ b/minimum-window-substring/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - public String minWindow(String S, String T) { - char[] s = S.toCharArray(); - char[] t = T.toCharArray(); - - if ( t.length == 0) return ""; - if ( t.length > s.length ) return ""; - - - int mstart = 0; - int mend = -1; - - int gstart = 0; - int gend = 0; - - int[] need = new int[256]; - int[] seen = new int[256]; - - int checksum = 0; - - for(char c : t){ - need[(int)c]++; - } - - for(/*void*/; gend < s.length; gend++ ){ - - int i = (int)s[gend]; - if(need[i] > 0){ - seen[i]++; - - if(seen[i] <= need[i]) - checksum++; - } - - - if(checksum == t.length){ - - if(mend < 0) mend = s.length - 1; - - for(/*void*/; gstart <= gend; gstart++){ - - i = (int)s[gstart]; - if(need[i] > 0){ - if( seen[i] > need[i] ){ - seen[i]--; - } else { - break; - } - } - } - - if(gend - gstart < mend - mstart ){ - mstart = gstart; - mend = gend; - } - - } - - } - - - return S.substring(mstart, mend + 1); - } +public class Solution { + public String minWindow(String S, String T) { + char[] s = S.toCharArray(); + char[] t = T.toCharArray(); + + if ( t.length == 0) return ""; + if ( t.length > s.length ) return ""; + + + int mstart = 0; + int mend = -1; + + int gstart = 0; + int gend = 0; + + int[] need = new int[256]; + int[] seen = new int[256]; + + int checksum = 0; + + for(char c : t){ + need[(int)c]++; + } + + for(/*void*/; gend < s.length; gend++ ){ + + int i = (int)s[gend]; + if(need[i] > 0){ + seen[i]++; + + if(seen[i] <= need[i]) + checksum++; + } + + + if(checksum == t.length){ + + if(mend < 0) mend = s.length - 1; + + for(/*void*/; gstart <= gend; gstart++){ + + i = (int)s[gstart]; + if(need[i] > 0){ + if( seen[i] > need[i] ){ + seen[i]--; + } else { + break; + } + } + } + + if(gend - gstart < mend - mstart ){ + mstart = gstart; + mend = gend; + } + + } + + } + + + return S.substring(mstart, mend + 1); + } } \ No newline at end of file diff --git a/missing-ranges/README.md b/missing-ranges/README.md index 69aaf0c..1c0fb88 100644 --- a/missing-ranges/README.md +++ b/missing-ranges/README.md @@ -1,63 +1,63 @@ -## Loop invariant - -init range is lower -> upper - -when a new number comes, the number divide the range into two ranges. -the left range must be a missing range. just output it. - - -``` -R = [0 -> 99] -S = [0, 1, 3, 50, 75] - ^ - | -``` - -`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` - -``` -R = [1 -> 99] -S = [1, 3, 50, 75] - ^ - | -``` - -`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` - -``` -R = [2 -> 99] -S = [3, 50, 75] - ^ - | -``` - -`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` - -`[2]` is a missing, output. - - -``` -R = [4 -> 99] -S = [50, 75] - ^ - | -``` - -`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` - -`[4 -> 49]` is a missing, output. - - -``` -R = [51 -> 99] -S = [75] - ^ - | -``` - -`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` - -`[51 -> 74]` is a missing, output. - - -the last one `[76 -> 99]` is a missing range too. +## Loop invariant + +init range is lower -> upper + +when a new number comes, the number divide the range into two ranges. +the left range must be a missing range. just output it. + + +``` +R = [0 -> 99] +S = [0, 1, 3, 50, 75] + ^ + | +``` + +`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` + +``` +R = [1 -> 99] +S = [1, 3, 50, 75] + ^ + | +``` + +`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` + +``` +R = [2 -> 99] +S = [3, 50, 75] + ^ + | +``` + +`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` + +`[2]` is a missing, output. + + +``` +R = [4 -> 99] +S = [50, 75] + ^ + | +``` + +`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` + +`[4 -> 49]` is a missing, output. + + +``` +R = [51 -> 99] +S = [75] + ^ + | +``` + +`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` + +`[51 -> 74]` is a missing, output. + + +the last one `[76 -> 99]` is a missing range too. diff --git a/multiply-strings/Solution.java b/multiply-strings/Solution.java index 7d2309d..b77b33e 100644 --- a/multiply-strings/Solution.java +++ b/multiply-strings/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public String multiply(String num1, String num2) { - - int[] paper = new int[num1.length() + num2.length()]; - - Arrays.fill(paper, 0); - - char[] _num1 = num1.toCharArray(); - char[] _num2 = num2.toCharArray(); - - for (int i = 0; i < _num2.length; i++) { - for (int j = 0; j < _num1.length; j++) { - paper[paper.length - (i + j + 2)] += (_num1[j] - '0') * (_num2[i] - '0'); - } - } - - - // add - - for (int i = 0; i < paper.length - 1; i++) { - paper[i + 1] += paper[i] / 10; - paper[i] %= 10; - - } - - String s = ""; - for(int i = paper.length - 1; i > 0 ; i--){ - - if(paper[i] == 0 && "".equals(s)) - continue; - - s += paper[i]; - } - - s += paper[0]; - - - return s; - - } +public class Solution { + public String multiply(String num1, String num2) { + + int[] paper = new int[num1.length() + num2.length()]; + + Arrays.fill(paper, 0); + + char[] _num1 = num1.toCharArray(); + char[] _num2 = num2.toCharArray(); + + for (int i = 0; i < _num2.length; i++) { + for (int j = 0; j < _num1.length; j++) { + paper[paper.length - (i + j + 2)] += (_num1[j] - '0') * (_num2[i] - '0'); + } + } + + + // add + + for (int i = 0; i < paper.length - 1; i++) { + paper[i + 1] += paper[i] / 10; + paper[i] %= 10; + + } + + String s = ""; + for(int i = paper.length - 1; i > 0 ; i--){ + + if(paper[i] == 0 && "".equals(s)) + continue; + + s += paper[i]; + } + + s += paper[0]; + + + return s; + + } } \ No newline at end of file diff --git a/n-queens-ii/Solution.java b/n-queens-ii/Solution.java index 7af34ef..ff737b8 100644 --- a/n-queens-ii/Solution.java +++ b/n-queens-ii/Solution.java @@ -1,58 +1,58 @@ -public class Solution { - - boolean[][] chessboard; - - int target; - - int rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - rt++; - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public int totalNQueens(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - chessboard = new boolean[n][n]; - target = n - 1; - - rt = 0; - - search(0); - - return rt; - } +public class Solution { + + boolean[][] chessboard; + + int target; + + int rt; + + boolean tryput(final int row, final int col){ + for(int i = row - 1; i >= 0; i--){ + int offset = row - i; + if(chessboard[i][col]) + return false; + + if(col - offset >= 0 && chessboard[i][col - offset]) + return false; + + if(col + offset <= target && chessboard[i][col + offset]) + return false; + } + + return true; + } + + void search(final int row){ + + if( row > target){ + + rt++; + + return; + } + + for(int i = 0; i <= target ; i++){ + if(tryput(row, i)){ + + chessboard[row][i] = true; + + search(row + 1); + + chessboard[row][i] = false; + } + } + + } + + public int totalNQueens(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + chessboard = new boolean[n][n]; + target = n - 1; + + rt = 0; + + search(0); + + return rt; + } } \ No newline at end of file diff --git a/n-queens/Solution.java b/n-queens/Solution.java index d6ff48b..7f28524 100644 --- a/n-queens/Solution.java +++ b/n-queens/Solution.java @@ -1,67 +1,67 @@ -public class Solution { - boolean[][] chessboard; - - int target; - - ArrayList rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - String[] valid = new String[target + 1]; - - for(int i = 0; i <= target ; i++){ - char[] s = new char[target + 1]; - for(int j = 0; j <= target; j++){ - s[j] = chessboard[i][j] ? 'Q' : '.'; - } - - valid[i] = new String(s); - } - - rt.add(valid); - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public List solveNQueens(int n) { - chessboard = new boolean[n][n]; - target = n - 1; - - rt = new ArrayList(); - - search(0); - - return rt; - } -} +public class Solution { + boolean[][] chessboard; + + int target; + + ArrayList rt; + + boolean tryput(final int row, final int col){ + for(int i = row - 1; i >= 0; i--){ + int offset = row - i; + if(chessboard[i][col]) + return false; + + if(col - offset >= 0 && chessboard[i][col - offset]) + return false; + + if(col + offset <= target && chessboard[i][col + offset]) + return false; + } + + return true; + } + + void search(final int row){ + + if( row > target){ + + String[] valid = new String[target + 1]; + + for(int i = 0; i <= target ; i++){ + char[] s = new char[target + 1]; + for(int j = 0; j <= target; j++){ + s[j] = chessboard[i][j] ? 'Q' : '.'; + } + + valid[i] = new String(s); + } + + rt.add(valid); + + return; + } + + for(int i = 0; i <= target ; i++){ + if(tryput(row, i)){ + + chessboard[row][i] = true; + + search(row + 1); + + chessboard[row][i] = false; + } + } + + } + + public List solveNQueens(int n) { + chessboard = new boolean[n][n]; + target = n - 1; + + rt = new ArrayList(); + + search(0); + + return rt; + } +} diff --git a/next-permutation/Solution.java b/next-permutation/Solution.java index b7d1b34..e0166e2 100644 --- a/next-permutation/Solution.java +++ b/next-permutation/Solution.java @@ -1,39 +1,39 @@ -public class Solution { - // http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public void nextPermutation(int[] num) { - - if(num.length < 2) return; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - } +public class Solution { + // http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html + void swap(int x[], int a, int b) { + int t = x[a]; + x[a] = x[b]; + x[b] = t; + } + + public void nextPermutation(int[] num) { + + if(num.length < 2) return; + + int p = -1; + + for(int i = num.length - 1; i >0; i--){ + if(num[i] > num[i - 1]){ + p = i - 1; + break; + } + } + + if(p == -1){ + Arrays.sort(num); + return; + } + + int c = -1; + for(int i = num.length - 1; i >=0; i--){ + if(num[i] > num[p]) { + c = i; + break; + } + } + + swap(num, p, c); + Arrays.sort(num, p + 1, num.length); + + } } \ No newline at end of file diff --git a/one-edit-distance/README.md b/one-edit-distance/README.md index 26004a9..2c95d72 100644 --- a/one-edit-distance/README.md +++ b/one-edit-distance/README.md @@ -1,26 +1,26 @@ -## [Edit Distance](../edit-distance) == 1 - -My first submission - - -``` -return minDistance(s, t) == 1; -``` - -but, leetcode shows `time limit exceeded`. - - -## Only 1 diff - -### Same length - -do one pass can know if there is only one different char - -### 1 char longer - -delete the redundant char will yield two same string - -Note: - -solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. - +## [Edit Distance](../edit-distance) == 1 + +My first submission + + +``` +return minDistance(s, t) == 1; +``` + +but, leetcode shows `time limit exceeded`. + + +## Only 1 diff + +### Same length + +do one pass can know if there is only one different char + +### 1 char longer + +delete the redundant char will yield two same string + +Note: + +solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. + diff --git a/palindrome-number/Solution.java b/palindrome-number/Solution.java index 074e10c..8578bb7 100644 --- a/palindrome-number/Solution.java +++ b/palindrome-number/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public boolean isPalindrome(int x) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - - if(x < 0) return false; - - if(x == 0) return true; - - int size = (int)Math.log10(x); - - int mid = size / 2; - - for(int i = 0; i <= mid; i++){ - - int p = (int) (x / Math.pow(10, i)) % 10; - int q = (int) (x / Math.pow(10, size - i)) % 10; - if(p != q) - return false; - - } - - return true; - } +public class Solution { + public boolean isPalindrome(int x) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + + if(x < 0) return false; + + if(x == 0) return true; + + int size = (int)Math.log10(x); + + int mid = size / 2; + + for(int i = 0; i <= mid; i++){ + + int p = (int) (x / Math.pow(10, i)) % 10; + int q = (int) (x / Math.pow(10, size - i)) % 10; + if(p != q) + return false; + + } + + return true; + } } \ No newline at end of file diff --git a/palindrome-partitioning-ii/Solution.java b/palindrome-partitioning-ii/Solution.java index 61922b0..d34fffd 100644 --- a/palindrome-partitioning-ii/Solution.java +++ b/palindrome-partitioning-ii/Solution.java @@ -1,49 +1,49 @@ -public class Solution { - public int minCut(String s) { - char[] S = s.toCharArray(); - - if(S.length == 0) return 0; - - boolean[][] P = new boolean[S.length][S.length]; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - P[2 - 1][i] = S[i] == S[i + 2 - 1]; - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - P[len - 1][i] = P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]; - } - } - - int[] mincut = new int[S.length + 1]; - - mincut[0] = 0; - mincut[1] = 0; - - for(int len = 2; len <= S.length; len++){ - - if(P[len - 1][0]){ - mincut[len] = 0; - }else{ - - mincut[len] = mincut[len - 1] + 1; - - for(int i = 1; i < len - 1; i++){ - - if(P[len - i - 1][i]){ - mincut[len] = Math.min(mincut[i] + 1 , mincut[len]); - } - } - } - } - - return mincut[S.length]; - } -} +public class Solution { + public int minCut(String s) { + char[] S = s.toCharArray(); + + if(S.length == 0) return 0; + + boolean[][] P = new boolean[S.length][S.length]; + + // len 1 + Arrays.fill(P[1 - 1], true); + + // len 2 + for(int i = 0; i < S.length - 1; i++){ + P[2 - 1][i] = S[i] == S[i + 2 - 1]; + } + + // len 3 to max + for(int len = 3; len <= S.length; len++){ + + for(int i = 0; i < S.length - (len - 1); i++){ + P[len - 1][i] = P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]; + } + } + + int[] mincut = new int[S.length + 1]; + + mincut[0] = 0; + mincut[1] = 0; + + for(int len = 2; len <= S.length; len++){ + + if(P[len - 1][0]){ + mincut[len] = 0; + }else{ + + mincut[len] = mincut[len - 1] + 1; + + for(int i = 1; i < len - 1; i++){ + + if(P[len - i - 1][i]){ + mincut[len] = Math.min(mincut[i] + 1 , mincut[len]); + } + } + } + } + + return mincut[S.length]; + } +} diff --git a/palindrome-partitioning/Solution.java b/palindrome-partitioning/Solution.java index 98a651e..db94c57 100644 --- a/palindrome-partitioning/Solution.java +++ b/palindrome-partitioning/Solution.java @@ -1,45 +1,45 @@ -public class Solution { - - boolean isPal(String s){ - - char[] S = s.toCharArray(); - - for(int i = 0; i < S.length / 2; i++){ - if(S[i] != S[S.length - i - 1]) - return false; - } - - return true; - } - - - - public List> partition(String s) { - - List> rt = new ArrayList>(); - - if("".equals(s)) return rt; - if(s.length() == 1) return Arrays.asList(Arrays.asList(s)); - - for(int i = 0; i < s.length(); i++){ - String x = s.substring(0, i + 1); - if(isPal(x)){ - List> sub = partition(s.substring(i + 1)); - - if(sub.isEmpty()){ - rt.add(Arrays.asList(x)); - } else { - for(List l : sub){ - ArrayList _l = new ArrayList(); - _l.add(x); - _l.addAll(l); - rt.add(_l); - } - } - } - } - - return rt; - - } +public class Solution { + + boolean isPal(String s){ + + char[] S = s.toCharArray(); + + for(int i = 0; i < S.length / 2; i++){ + if(S[i] != S[S.length - i - 1]) + return false; + } + + return true; + } + + + + public List> partition(String s) { + + List> rt = new ArrayList>(); + + if("".equals(s)) return rt; + if(s.length() == 1) return Arrays.asList(Arrays.asList(s)); + + for(int i = 0; i < s.length(); i++){ + String x = s.substring(0, i + 1); + if(isPal(x)){ + List> sub = partition(s.substring(i + 1)); + + if(sub.isEmpty()){ + rt.add(Arrays.asList(x)); + } else { + for(List l : sub){ + ArrayList _l = new ArrayList(); + _l.add(x); + _l.addAll(l); + rt.add(_l); + } + } + } + } + + return rt; + + } } \ No newline at end of file diff --git a/partition-list/Solution.java b/partition-list/Solution.java index a0abea8..4580a4b 100644 --- a/partition-list/Solution.java +++ b/partition-list/Solution.java @@ -1,43 +1,43 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode partition(ListNode head, int x) { - if(head == null) return null; - if(head.next == null) return head; - - final ListNode less = new ListNode(0); - final ListNode greater = new ListNode(0); - - ListNode _less = less; - ListNode _greater = greater; - - while(head != null){ - ListNode t = head; - head = head.next; - - if(t.val < x){ - _less.next = t; - _less = _less.next; - }else { - _greater.next = t; - _greater = _greater.next; - } - } - - _greater.next = null; - - _less.next = greater.next; - - return less.next; - - } -} +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode partition(ListNode head, int x) { + if(head == null) return null; + if(head.next == null) return head; + + final ListNode less = new ListNode(0); + final ListNode greater = new ListNode(0); + + ListNode _less = less; + ListNode _greater = greater; + + while(head != null){ + ListNode t = head; + head = head.next; + + if(t.val < x){ + _less.next = t; + _less = _less.next; + }else { + _greater.next = t; + _greater = _greater.next; + } + } + + _greater.next = null; + + _less.next = greater.next; + + return less.next; + + } +} diff --git a/pascals-triangle-ii/Solution.java b/pascals-triangle-ii/Solution.java index 86aefa4..dd8a4ba 100644 --- a/pascals-triangle-ii/Solution.java +++ b/pascals-triangle-ii/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public List getRow(int rowIndex) { - Integer[] row = new Integer[rowIndex + 1]; - - Arrays.fill(row, 1); - - for(int i = 0 ; i < rowIndex - 1; i++){ - for(int j = i + 1; j >= 1; j--){ - row[j] = row[j] + row[j - 1]; - } - } - - return Arrays.asList(row); - } -} +public class Solution { + public List getRow(int rowIndex) { + Integer[] row = new Integer[rowIndex + 1]; + + Arrays.fill(row, 1); + + for(int i = 0 ; i < rowIndex - 1; i++){ + for(int j = i + 1; j >= 1; j--){ + row[j] = row[j] + row[j - 1]; + } + } + + return Arrays.asList(row); + } +} diff --git a/pascals-triangle/Solution.java b/pascals-triangle/Solution.java index 77ad926..503e03d 100644 --- a/pascals-triangle/Solution.java +++ b/pascals-triangle/Solution.java @@ -1,28 +1,28 @@ -public class Solution { - public List> generate(int numRows) { - - ArrayList> rt = new ArrayList>(); - - Integer[] prev = null; - - for(int i = 1 ; i <= numRows; i++){ - - Integer[] row = new Integer[i]; - - row[0] = 1; - row[i - 1] = 1; - - for(int j = 1; j < i - 1 ; j++){ - //row.add(j, prev.get(j) + prev.get(j -1)); - row[j] = prev[j] + prev[j - 1]; - } - - rt.add(new ArrayList(Arrays.asList(row))); - prev = row; - } - - - return rt; - - } -} +public class Solution { + public List> generate(int numRows) { + + ArrayList> rt = new ArrayList>(); + + Integer[] prev = null; + + for(int i = 1 ; i <= numRows; i++){ + + Integer[] row = new Integer[i]; + + row[0] = 1; + row[i - 1] = 1; + + for(int j = 1; j < i - 1 ; j++){ + //row.add(j, prev.get(j) + prev.get(j -1)); + row[j] = prev[j] + prev[j - 1]; + } + + rt.add(new ArrayList(Arrays.asList(row))); + prev = row; + } + + + return rt; + + } +} diff --git a/path-sum-ii/Solution.java b/path-sum-ii/Solution.java index c3186f2..ab9ab8a 100644 --- a/path-sum-ii/Solution.java +++ b/path-sum-ii/Solution.java @@ -1,44 +1,44 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - void addIfNotEmpty(List> rt, List> l){ - if(!l.isEmpty()){ - rt.addAll(l); - } - } - - List> pathSum(TreeNode root, int sum, List parents) { - List> rt = new ArrayList>(); - - if(root == null) return rt; - - ArrayList p = new ArrayList(parents); - p.add(root.val); - - if(root.left == null & root.right == null){ - if(root.val == sum){ - rt.add(p); - } - - return rt; - } - - addIfNotEmpty(rt, pathSum(root.left, sum - root.val, p)); - addIfNotEmpty(rt, pathSum(root.right, sum - root.val, p)); - - return rt; - } - - public List> pathSum(TreeNode root, int sum) { - - return pathSum(root, sum, new ArrayList()); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + void addIfNotEmpty(List> rt, List> l){ + if(!l.isEmpty()){ + rt.addAll(l); + } + } + + List> pathSum(TreeNode root, int sum, List parents) { + List> rt = new ArrayList>(); + + if(root == null) return rt; + + ArrayList p = new ArrayList(parents); + p.add(root.val); + + if(root.left == null & root.right == null){ + if(root.val == sum){ + rt.add(p); + } + + return rt; + } + + addIfNotEmpty(rt, pathSum(root.left, sum - root.val, p)); + addIfNotEmpty(rt, pathSum(root.right, sum - root.val, p)); + + return rt; + } + + public List> pathSum(TreeNode root, int sum) { + + return pathSum(root, sum, new ArrayList()); + } +} diff --git a/path-sum/Solution.java b/path-sum/Solution.java index aef077b..02715bf 100644 --- a/path-sum/Solution.java +++ b/path-sum/Solution.java @@ -1,27 +1,27 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - - - public boolean hasPathSum(TreeNode root, int sum) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (root == null) - return false; - - if (root.left == null && root.right == null) //leaf - return root.val == sum; - - return (root.left != null && hasPathSum(root.left, sum - root.val)) - || (root.right != null && hasPathSum(root.right, sum - root.val)); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + + + public boolean hasPathSum(TreeNode root, int sum) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if (root == null) + return false; + + if (root.left == null && root.right == null) //leaf + return root.val == sum; + + return (root.left != null && hasPathSum(root.left, sum - root.val)) + || (root.right != null && hasPathSum(root.right, sum - root.val)); + } } \ No newline at end of file diff --git a/permutation-sequence/Solution.java b/permutation-sequence/Solution.java index 7348fe2..ce7abe3 100644 --- a/permutation-sequence/Solution.java +++ b/permutation-sequence/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - - int fact(int x){ - int s = 1; - - for(int i = 1; i <= x; i++) - s *= i; - - return s; - } - - public String getPermutation(int n, int k) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ArrayList chars = new ArrayList(); - - for(int i = '1'; i <('1' + n); i++) - chars.add((char)i); - - k -= 1; - - char[] t = new char[n]; - int l = 0; - - for(int i = n - 1; i > 0; i--){ - int f = fact(i); - - int c = k / f; - - t[l++] = chars.get(c); - chars.remove(c); - - k %= f; - } - - t[n - 1] = chars.get(0); - - return new String(t); - - } +public class Solution { + + int fact(int x){ + int s = 1; + + for(int i = 1; i <= x; i++) + s *= i; + + return s; + } + + public String getPermutation(int n, int k) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ArrayList chars = new ArrayList(); + + for(int i = '1'; i <('1' + n); i++) + chars.add((char)i); + + k -= 1; + + char[] t = new char[n]; + int l = 0; + + for(int i = n - 1; i > 0; i--){ + int f = fact(i); + + int c = k / f; + + t[l++] = chars.get(c); + chars.remove(c); + + k %= f; + } + + t[n - 1] = chars.get(0); + + return new String(t); + + } } \ No newline at end of file diff --git a/permutations-ii/Solution.java b/permutations-ii/Solution.java index eae0ae2..a0d2b4c 100644 --- a/permutations-ii/Solution.java +++ b/permutations-ii/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public boolean nextPermutation(int[] num) { - - if(num.length < 2) return false; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return false; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - return true; - } - - List asList(int[] num){ - ArrayList l = new ArrayList(num.length); - for(int i = 0; i < num.length; i++) - l.add(num[i]); - - return l; - } - - public List> permuteUnique(int[] num) { - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - found.add(asList(num)); - - while(nextPermutation(num)){ - found.add(asList(num)); - } - - return found; - } -} +public class Solution { + + void swap(int x[], int a, int b) { + int t = x[a]; + x[a] = x[b]; + x[b] = t; + } + + public boolean nextPermutation(int[] num) { + + if(num.length < 2) return false; + + int p = -1; + + for(int i = num.length - 1; i >0; i--){ + if(num[i] > num[i - 1]){ + p = i - 1; + break; + } + } + + if(p == -1){ + Arrays.sort(num); + return false; + } + + int c = -1; + for(int i = num.length - 1; i >=0; i--){ + if(num[i] > num[p]) { + c = i; + break; + } + } + + swap(num, p, c); + Arrays.sort(num, p + 1, num.length); + + return true; + } + + List asList(int[] num){ + ArrayList l = new ArrayList(num.length); + for(int i = 0; i < num.length; i++) + l.add(num[i]); + + return l; + } + + public List> permuteUnique(int[] num) { + Arrays.sort(num); + + ArrayList> found = new ArrayList>(); + found.add(asList(num)); + + while(nextPermutation(num)){ + found.add(asList(num)); + } + + return found; + } +} diff --git a/permutations/Solution.java b/permutations/Solution.java index b9112cc..a1e1ae7 100644 --- a/permutations/Solution.java +++ b/permutations/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - - int[] resetof(int[] num, int index){ - int[] rt = new int[num.length - 1]; - int s = 0; - for(int i = 0; i < num.length ; i++) - if(i != index) rt[s++] = num[i]; - - return rt; - } - - public List> permute(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if(num.length == 0){ - // do nothing - }else if(num.length == 1) { - rt.add(new ArrayList(Arrays.asList(num[0]))); - }else{ - - for(int i = 0; i < num.length; i++){ - for(List l : permute(resetof(num, i))){ - l.add(num[i]); - rt.add(l); - }; - } - - } - - return rt; - - - } -} +public class Solution { + + int[] resetof(int[] num, int index){ + int[] rt = new int[num.length - 1]; + int s = 0; + for(int i = 0; i < num.length ; i++) + if(i != index) rt[s++] = num[i]; + + return rt; + } + + public List> permute(int[] num) { + + ArrayList> rt = new ArrayList>(); + + if(num.length == 0){ + // do nothing + }else if(num.length == 1) { + rt.add(new ArrayList(Arrays.asList(num[0]))); + }else{ + + for(int i = 0; i < num.length; i++){ + for(List l : permute(resetof(num, i))){ + l.add(num[i]); + rt.add(l); + }; + } + + } + + return rt; + + + } +} diff --git a/plus-one/Solution.java b/plus-one/Solution.java index 1908d68..e31cd2c 100644 --- a/plus-one/Solution.java +++ b/plus-one/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public int[] plusOne(int[] digits) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int[] result = new int[digits.length + 1]; - digits[digits.length - 1] += 1; - for(int i = digits.length - 1; i >=0 ; i--){ - result[ i + 1 ] += digits[i]; - result[ i ] += result[ i + 1 ] / 10; - result[ i + 1 ] %= 10; - } - - if(result[0] == 0) return Arrays.copyOfRange(result, 1 , result.length); - else - return result; - } +public class Solution { + public int[] plusOne(int[] digits) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + int[] result = new int[digits.length + 1]; + digits[digits.length - 1] += 1; + for(int i = digits.length - 1; i >=0 ; i--){ + result[ i + 1 ] += digits[i]; + result[ i ] += result[ i + 1 ] / 10; + result[ i + 1 ] %= 10; + } + + if(result[0] == 0) return Arrays.copyOfRange(result, 1 , result.length); + else + return result; + } } \ No newline at end of file diff --git a/populating-next-right-pointers-in-each-node-ii/Solution.java b/populating-next-right-pointers-in-each-node-ii/Solution.java index 8ed1a81..a470db6 100644 --- a/populating-next-right-pointers-in-each-node-ii/Solution.java +++ b/populating-next-right-pointers-in-each-node-ii/Solution.java @@ -1,47 +1,47 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeLinkNode ORPHAN = new TreeLinkNode(0); - - TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){ - - if(parent == null) return null; - - if(parent.left != null && parent.left != me){ - return parent.left; - } - - if(parent.right != null){ - return parent.right; - } - - return sib(ORPHAN, parent.next); - - } - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - if(root.left != null){ - root.left.next = sib(root.left, root); - } - - - if(root.right != null){ - root.right.next = sib(ORPHAN, root.next); - } - - connect(root.right); - connect(root.left); - - - } +/** + * Definition for binary tree with next pointer. + * public class TreeLinkNode { + * int val; + * TreeLinkNode left, right, next; + * TreeLinkNode(int x) { val = x; } + * } + */ +public class Solution { + + static final TreeLinkNode ORPHAN = new TreeLinkNode(0); + + TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){ + + if(parent == null) return null; + + if(parent.left != null && parent.left != me){ + return parent.left; + } + + if(parent.right != null){ + return parent.right; + } + + return sib(ORPHAN, parent.next); + + } + + public void connect(TreeLinkNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null) return; + + if(root.left != null){ + root.left.next = sib(root.left, root); + } + + + if(root.right != null){ + root.right.next = sib(ORPHAN, root.next); + } + + connect(root.right); + connect(root.left); + + + } } \ No newline at end of file diff --git a/populating-next-right-pointers-in-each-node/Solution.java b/populating-next-right-pointers-in-each-node/Solution.java index 9c92d20..7dcfb82 100644 --- a/populating-next-right-pointers-in-each-node/Solution.java +++ b/populating-next-right-pointers-in-each-node/Solution.java @@ -1,26 +1,26 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null || root.left == null || root.right == null) return; - - root.left.next = root.right; - - if(root.next != null){ - root.right.next = root.next.left; - } - - connect(root.left); - connect(root.right); - - } +/** + * Definition for binary tree with next pointer. + * public class TreeLinkNode { + * int val; + * TreeLinkNode left, right, next; + * TreeLinkNode(int x) { val = x; } + * } + */ +public class Solution { + + + public void connect(TreeLinkNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null || root.left == null || root.right == null) return; + + root.left.next = root.right; + + if(root.next != null){ + root.right.next = root.next.left; + } + + connect(root.left); + connect(root.right); + + } } \ No newline at end of file diff --git a/powx-n/Solution.java b/powx-n/Solution.java index 54ffa89..f8e8026 100644 --- a/powx-n/Solution.java +++ b/powx-n/Solution.java @@ -1,17 +1,17 @@ -public class Solution { - public double pow(double x, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(n == 0) return 1; - - double s = pow(x, n /2); - - if(n % 2 == 0) - return s * s; - else if(n > 0) - return s * s * x; - else - return s * s / x; - - - } -} +public class Solution { + public double pow(double x, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(n == 0) return 1; + + double s = pow(x, n /2); + + if(n % 2 == 0) + return s * s; + else if(n > 0) + return s * s * x; + else + return s * s / x; + + + } +} diff --git a/read-n-characters-given-read4-ii-call-multiple-times/README.md b/read-n-characters-given-read4-ii-call-multiple-times/README.md index 5118d2e..81e0be1 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/README.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/README.md @@ -1,23 +1,23 @@ -## EAGAIN and read - -This is a common problem in real world. -when client read some data from server, data will not always be available to be read. -`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, -call me later. - -## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) - -when you call `read4`, it might return 4 `char`s. -however, the `read` only ask you for 1 `char`. -you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. - -to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. - -``` - | just store these two chars for coming read call - V - .... .... .... ..** .... .. -[++++ ++++ ++++ ++][ ++++ +] - -``` - +## EAGAIN and read + +This is a common problem in real world. +when client read some data from server, data will not always be available to be read. +`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, +call me later. + +## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) + +when you call `read4`, it might return 4 `char`s. +however, the `read` only ask you for 1 `char`. +you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. + +to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. + +``` + | just store these two chars for coming read call + V + .... .... .... ..** .... .. +[++++ ++++ ++++ ++][ ++++ +] + +``` + diff --git a/read-n-characters-given-read4/README.md b/read-n-characters-given-read4/README.md index 69203bc..40f4900 100644 --- a/read-n-characters-given-read4/README.md +++ b/read-n-characters-given-read4/README.md @@ -1,14 +1,14 @@ -## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full - - -``` -.... .... .... ...E <- data read4 -++++ ++++ ++++ ++ <- data pipe to read -``` - -code should be like below - -``` -while not EOF or buf not full - append read4 to buf -``` +## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full + + +``` +.... .... .... ...E <- data read4 +++++ ++++ ++++ ++ <- data pipe to read +``` + +code should be like below + +``` +while not EOF or buf not full + append read4 to buf +``` diff --git a/recover-binary-search-tree/Solution.java b/recover-binary-search-tree/Solution.java index dd2ef22..f3813ec 100644 --- a/recover-binary-search-tree/Solution.java +++ b/recover-binary-search-tree/Solution.java @@ -1,53 +1,53 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode[] bad; - TreeNode last; - - - void inorder(TreeNode root){ - - if(root.left != null) inorder(root.left); - - if(last != null && last.val > root.val){ // - bad[0] = root; - - if(bad[1] == null) bad[1] = last; - } - - last = root; - - - if(root.right != null) inorder(root.right); - - } - - public void recoverTree(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - bad = new TreeNode[2]; - bad[0] = null; - bad[1] = null; - last = null; - - inorder(root); - - - if(bad[0] != null && bad[1] != null){ - int t = bad[0].val; - bad[0].val = bad[1].val; - bad[1].val = t; - } - - - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode[] bad; + TreeNode last; + + + void inorder(TreeNode root){ + + if(root.left != null) inorder(root.left); + + if(last != null && last.val > root.val){ // + bad[0] = root; + + if(bad[1] == null) bad[1] = last; + } + + last = root; + + + if(root.right != null) inorder(root.right); + + } + + public void recoverTree(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(root == null) return; + + bad = new TreeNode[2]; + bad[0] = null; + bad[1] = null; + last = null; + + inorder(root); + + + if(bad[0] != null && bad[1] != null){ + int t = bad[0].val; + bad[0].val = bad[1].val; + bad[1].val = t; + } + + + } } \ No newline at end of file diff --git a/regular-expression-matching/Solution.java b/regular-expression-matching/Solution.java index 6b997d4..3140552 100644 --- a/regular-expression-matching/Solution.java +++ b/regular-expression-matching/Solution.java @@ -1,232 +1,232 @@ -public class Solution { - static final Character EPSILON = 0; - - static class State{ - - static Set allchar = new HashSet(); - - boolean end; - - Map> next = new HashMap>(); - - State(){ - this(false); - } - - State(boolean end){ - this.end = end; - } - - State match(Character c) { - Set states = next.get(c); - - if(states == null){ - states = next.get('.'); - } - - if(states != null) { - for (State s : states) { - return s; - } - } - - return null; - } - - Set matchAll(Character c) { - Set match = next.get(c); - - return match; - } - - void addNext(Character c, State s){ - - if(c != EPSILON) - allchar.add(c); - - Set l = next.get(c); - - if(l == null){ - l = new HashSet(); - next.put(c, l); - } - - l.add(s); - } - } - - State nfa(char[] pattern){ - - final State end = new State(true); - - State last = end; - - for(int i = pattern.length - 1; i >= 0; i--){ - if(pattern[i] == '*'){ - i--; - - State s1 = new State(); - State s2 = new State(); - State s3 = new State(); - State s4 = last; - - s1.addNext(EPSILON, s2); - s1.addNext(EPSILON, s4); - - s2.addNext(pattern[i], s3); - - s3.addNext(EPSILON, s4); - - s4.addNext(EPSILON, s2); - - last = s1; - - }else{ - State curr = new State(); - curr.addNext(pattern[i], last); - last = curr; - } - } - - - return last; - } - - boolean end(Set states){ - for (State state : states) { - if(state.end){ - return true; - } - } - return false; - } - - State dfa(State start){ - - Map, HashMap>> table = new HashMap, HashMap>>(); - Map, State> toone = new HashMap, State>(); - - final Set enter = allEpslilon(Collections.singleton(start)); - - LinkedList> queue = new LinkedList>(); - queue.add(enter); - - while(!queue.isEmpty()){ - - Set key = queue.poll(); - - if(!toone.containsKey(key)){ - State maps = new State(); - maps.end = end(key); - - toone.put(key, maps); - } - - HashMap> targets = searchTarget(key); - table.put(key, targets); - - for (Set states : targets.values()) { - if(table.get(states) == null){ - queue.add(states); - } - } - - } - - for (Map.Entry, HashMap>> entry : table.entrySet()) { - State s = toone.get(entry.getKey()); - - for (Map.Entry> t : entry.getValue().entrySet()) { - s.addNext(t.getKey(), toone.get(t.getValue())); - } - - } - - return toone.get(enter); - } - - HashMap> searchTarget(Set form) { - HashMap> targets = new HashMap>(); - - for(State s : form) { - for (Character c : State.allchar) { - Set ns = s.matchAll(c); - - if (ns == null) continue; - - Set states = allEpslilon(ns); - - Set t = targets.get(c); - if(t == null){ - t = new HashSet(); - targets.put(c, t); - } - - t.addAll(states); - - } - } - - return targets; - } - - Set allEpslilon(Set ns) { - Set states = new HashSet(); - states.addAll(ns); - - - int oldsize = 0; - - - while (states.size() != oldsize) { - - oldsize = states.size(); - - Set temp = new HashSet(); - - for (State target : states) { - Set t = target.matchAll(EPSILON); - if (t != null) temp.addAll(t); - } - - states.addAll(temp); - - } - return states; - } - - boolean isMatch(char[] s, State state, int p){ - - if(state == null){ - return false; - } - - if(p >= s.length){ - return state.end; - } - - for (Map.Entry> entry : state.next.entrySet()) { - - Character key = entry.getKey(); - if(key.equals(s[p]) || key.equals('.')){ - if(isMatch(s, entry.getValue().iterator().next(), p + 1)){ - return true; - } - } - } - - return false; - } - - public boolean isMatch(String s, String p) { - - State.allchar = new HashSet(); - - State state = nfa(p.toCharArray()); - state = dfa(state); - - char[] chars = s.toCharArray(); - - return isMatch(chars, state, 0); - } +public class Solution { + static final Character EPSILON = 0; + + static class State{ + + static Set allchar = new HashSet(); + + boolean end; + + Map> next = new HashMap>(); + + State(){ + this(false); + } + + State(boolean end){ + this.end = end; + } + + State match(Character c) { + Set states = next.get(c); + + if(states == null){ + states = next.get('.'); + } + + if(states != null) { + for (State s : states) { + return s; + } + } + + return null; + } + + Set matchAll(Character c) { + Set match = next.get(c); + + return match; + } + + void addNext(Character c, State s){ + + if(c != EPSILON) + allchar.add(c); + + Set l = next.get(c); + + if(l == null){ + l = new HashSet(); + next.put(c, l); + } + + l.add(s); + } + } + + State nfa(char[] pattern){ + + final State end = new State(true); + + State last = end; + + for(int i = pattern.length - 1; i >= 0; i--){ + if(pattern[i] == '*'){ + i--; + + State s1 = new State(); + State s2 = new State(); + State s3 = new State(); + State s4 = last; + + s1.addNext(EPSILON, s2); + s1.addNext(EPSILON, s4); + + s2.addNext(pattern[i], s3); + + s3.addNext(EPSILON, s4); + + s4.addNext(EPSILON, s2); + + last = s1; + + }else{ + State curr = new State(); + curr.addNext(pattern[i], last); + last = curr; + } + } + + + return last; + } + + boolean end(Set states){ + for (State state : states) { + if(state.end){ + return true; + } + } + return false; + } + + State dfa(State start){ + + Map, HashMap>> table = new HashMap, HashMap>>(); + Map, State> toone = new HashMap, State>(); + + final Set enter = allEpslilon(Collections.singleton(start)); + + LinkedList> queue = new LinkedList>(); + queue.add(enter); + + while(!queue.isEmpty()){ + + Set key = queue.poll(); + + if(!toone.containsKey(key)){ + State maps = new State(); + maps.end = end(key); + + toone.put(key, maps); + } + + HashMap> targets = searchTarget(key); + table.put(key, targets); + + for (Set states : targets.values()) { + if(table.get(states) == null){ + queue.add(states); + } + } + + } + + for (Map.Entry, HashMap>> entry : table.entrySet()) { + State s = toone.get(entry.getKey()); + + for (Map.Entry> t : entry.getValue().entrySet()) { + s.addNext(t.getKey(), toone.get(t.getValue())); + } + + } + + return toone.get(enter); + } + + HashMap> searchTarget(Set form) { + HashMap> targets = new HashMap>(); + + for(State s : form) { + for (Character c : State.allchar) { + Set ns = s.matchAll(c); + + if (ns == null) continue; + + Set states = allEpslilon(ns); + + Set t = targets.get(c); + if(t == null){ + t = new HashSet(); + targets.put(c, t); + } + + t.addAll(states); + + } + } + + return targets; + } + + Set allEpslilon(Set ns) { + Set states = new HashSet(); + states.addAll(ns); + + + int oldsize = 0; + + + while (states.size() != oldsize) { + + oldsize = states.size(); + + Set temp = new HashSet(); + + for (State target : states) { + Set t = target.matchAll(EPSILON); + if (t != null) temp.addAll(t); + } + + states.addAll(temp); + + } + return states; + } + + boolean isMatch(char[] s, State state, int p){ + + if(state == null){ + return false; + } + + if(p >= s.length){ + return state.end; + } + + for (Map.Entry> entry : state.next.entrySet()) { + + Character key = entry.getKey(); + if(key.equals(s[p]) || key.equals('.')){ + if(isMatch(s, entry.getValue().iterator().next(), p + 1)){ + return true; + } + } + } + + return false; + } + + public boolean isMatch(String s, String p) { + + State.allchar = new HashSet(); + + State state = nfa(p.toCharArray()); + state = dfa(state); + + char[] chars = s.toCharArray(); + + return isMatch(chars, state, 0); + } } \ No newline at end of file diff --git a/remove-duplicates-from-sorted-array-ii/Solution.java b/remove-duplicates-from-sorted-array-ii/Solution.java index 4e9e4bb..54ca064 100644 --- a/remove-duplicates-from-sorted-array-ii/Solution.java +++ b/remove-duplicates-from-sorted-array-ii/Solution.java @@ -1,25 +1,25 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(A.length == 0) return 0; - - int len = 1; - int lastseencount = 0; - - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]){ - - for(int j = i - 1; j > len + Math.min(lastseencount, 1) - 1 ; j--) - A[j] = A[i]; - - len += Math.min(lastseencount, 1) + 1; - lastseencount = 0; - }else{ - lastseencount++; - } - } - - return len + Math.min(lastseencount, 1); - } +public class Solution { + public int removeDuplicates(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(A.length == 0) return 0; + + int len = 1; + int lastseencount = 0; + + for(int i = 1; i< A.length; i++){ + if(A[i] != A[i - 1]){ + + for(int j = i - 1; j > len + Math.min(lastseencount, 1) - 1 ; j--) + A[j] = A[i]; + + len += Math.min(lastseencount, 1) + 1; + lastseencount = 0; + }else{ + lastseencount++; + } + } + + return len + Math.min(lastseencount, 1); + } } \ No newline at end of file diff --git a/remove-duplicates-from-sorted-array/Solution.java b/remove-duplicates-from-sorted-array/Solution.java index bc6acb4..3edcc3e 100644 --- a/remove-duplicates-from-sorted-array/Solution.java +++ b/remove-duplicates-from-sorted-array/Solution.java @@ -1,19 +1,19 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if (A.length == 0) return 0; - - int len = 1; - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]) { - for(int j = i - 1 ; j > len - 1 ; j-- ) - A[j] = A[i]; - - len++; - } - } - - return len; - } +public class Solution { + public int removeDuplicates(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if (A.length == 0) return 0; + + int len = 1; + for(int i = 1; i< A.length; i++){ + if(A[i] != A[i - 1]) { + for(int j = i - 1 ; j > len - 1 ; j-- ) + A[j] = A[i]; + + len++; + } + } + + return len; + } } \ No newline at end of file diff --git a/remove-duplicates-from-sorted-list-ii/Solution.java b/remove-duplicates-from-sorted-list-ii/Solution.java index 2c5121d..06e5fec 100644 --- a/remove-duplicates-from-sorted-list-ii/Solution.java +++ b/remove-duplicates-from-sorted-list-ii/Solution.java @@ -1,37 +1,37 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head; - - boolean killme = false; - while(node.next != null && node.next.val == v){ - node = node.next; - killme = true; - } - - if(killme) - head = deleteDuplicates(node.next); - else - head.next = deleteDuplicates(node.next); - - return head; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode deleteDuplicates(ListNode head) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + if(head.next == null) return head; + + int v = head.val; + + ListNode node = head; + + boolean killme = false; + while(node.next != null && node.next.val == v){ + node = node.next; + killme = true; + } + + if(killme) + head = deleteDuplicates(node.next); + else + head.next = deleteDuplicates(node.next); + + return head; + + } } \ No newline at end of file diff --git a/remove-duplicates-from-sorted-list/Solution.java b/remove-duplicates-from-sorted-list/Solution.java index 9c78398..badf567 100644 --- a/remove-duplicates-from-sorted-list/Solution.java +++ b/remove-duplicates-from-sorted-list/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head.next; - ListNode lasthead = head; - while(node != null){ - - while(node != null && node.val == lasthead.val) node = node.next; - - lasthead.next = node; - lasthead = node; - - if(node != null) node = node.next; - - } - - return head; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode deleteDuplicates(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return null; + if(head.next == null) return head; + + int v = head.val; + + ListNode node = head.next; + ListNode lasthead = head; + while(node != null){ + + while(node != null && node.val == lasthead.val) node = node.next; + + lasthead.next = node; + lasthead = node; + + if(node != null) node = node.next; + + } + + return head; + } } \ No newline at end of file diff --git a/remove-element/Solution.java b/remove-element/Solution.java index a632df9..fe31570 100644 --- a/remove-element/Solution.java +++ b/remove-element/Solution.java @@ -1,16 +1,16 @@ -public class Solution { - public int removeElement(int[] A, int elem) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(A.length == 0) return 0; - - int len = 0; - - for(int i = 0; i< A.length; i++){ - if(A[i] != elem) A[len++] = A[i]; - } - - - return len; - } +public class Solution { + public int removeElement(int[] A, int elem) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(A.length == 0) return 0; + + int len = 0; + + for(int i = 0; i< A.length; i++){ + if(A[i] != elem) A[len++] = A[i]; + } + + + return len; + } } \ No newline at end of file diff --git a/remove-nth-node-from-end-of-list/Solution.java b/remove-nth-node-from-end-of-list/Solution.java index 4998282..063465a 100644 --- a/remove-nth-node-from-end-of-list/Solution.java +++ b/remove-nth-node-from-end-of-list/Solution.java @@ -1,36 +1,36 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - final ListNode _head = new ListNode(0); - _head.next = head; - - ListNode fast = _head; - ListNode slow = _head; - - for(int i = 0; i< n ; i++) fast = fast.next; - - while(fast != null && fast.next != null){ - fast = fast.next; - slow = slow.next; - } - - slow.next = slow.next.next; - - return _head.next; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + + final ListNode _head = new ListNode(0); + _head.next = head; + + ListNode fast = _head; + ListNode slow = _head; + + for(int i = 0; i< n ; i++) fast = fast.next; + + while(fast != null && fast.next != null){ + fast = fast.next; + slow = slow.next; + } + + slow.next = slow.next.next; + + return _head.next; + } } \ No newline at end of file diff --git a/reorder-list/Solution.java b/reorder-list/Solution.java index b6fa642..547df74 100644 --- a/reorder-list/Solution.java +++ b/reorder-list/Solution.java @@ -1,75 +1,75 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode reverse(ListNode head){ - ListNode prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode mid(ListNode head){ - - ListNode fast = head; - ListNode slow = head; - - while(fast != null && fast.next != null){ - fast = fast.next.next; - slow = slow.next; - } - - return slow; - } - - public void reorderList(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return; - if(head.next == null) return; - - ListNode left = head; - - ListNode mid = mid(head); - - ListNode right = mid.next; - - if(right == null) return; - - mid.next = null; - - right = reverse(right); - - while(head != null){ - ListNode t = head.next; - - ListNode r = right; - - if(r == null) return; - - head.next = r; - right = right.next; - r.next = t; - - head = t; - } - - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + ListNode reverse(ListNode head){ + ListNode prev = null; + + while(head != null){ + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + + ListNode mid(ListNode head){ + + ListNode fast = head; + ListNode slow = head; + + while(fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + } + + return slow; + } + + public void reorderList(ListNode head) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + if(head == null) return; + if(head.next == null) return; + + ListNode left = head; + + ListNode mid = mid(head); + + ListNode right = mid.next; + + if(right == null) return; + + mid.next = null; + + right = reverse(right); + + while(head != null){ + ListNode t = head.next; + + ListNode r = right; + + if(r == null) return; + + head.next = r; + right = right.next; + r.next = t; + + head = t; + } + + } } \ No newline at end of file diff --git a/restore-ip-addresses/Solution.java b/restore-ip-addresses/Solution.java index cd549f8..97f46f4 100644 --- a/restore-ip-addresses/Solution.java +++ b/restore-ip-addresses/Solution.java @@ -1,46 +1,46 @@ -public class Solution { - - ArrayList collect; - - String[] stack; - - void findnum(String s, int p, int pstack){ - - if(pstack == 4){ - - if(p >= s.length()){ - String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; - - collect.add(ip); - } - - return; - } - - for(int i = 1; i <= 3; i++){ - - if( p + i > s.length()) - return; - - String number = s.substring(p, p + i); - - if(i > 1 && s.charAt(p) == '0') continue; - - if(Integer.parseInt(number) <= 255){ - stack[pstack] = number; - findnum(s, p + i, pstack + 1); - } - - } - } - - public List restoreIpAddresses(String s) { - - collect = new ArrayList(); - stack = new String[4]; - - findnum(s, 0 , 0); - - return collect; - } -} +public class Solution { + + ArrayList collect; + + String[] stack; + + void findnum(String s, int p, int pstack){ + + if(pstack == 4){ + + if(p >= s.length()){ + String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; + + collect.add(ip); + } + + return; + } + + for(int i = 1; i <= 3; i++){ + + if( p + i > s.length()) + return; + + String number = s.substring(p, p + i); + + if(i > 1 && s.charAt(p) == '0') continue; + + if(Integer.parseInt(number) <= 255){ + stack[pstack] = number; + findnum(s, p + i, pstack + 1); + } + + } + } + + public List restoreIpAddresses(String s) { + + collect = new ArrayList(); + stack = new String[4]; + + findnum(s, 0 , 0); + + return collect; + } +} diff --git a/reverse-integer/Solution.java b/reverse-integer/Solution.java index d9b4d6e..7d0fb3c 100644 --- a/reverse-integer/Solution.java +++ b/reverse-integer/Solution.java @@ -1,23 +1,23 @@ -public class Solution { - public int reverse(int x) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(x == 0) return 0; - if(x < 0) return -reverse(-x); - - int len = (int)Math.log10(x) + 1; - int[] y = new int[len]; - - int i = 0; - while(i < len){ - y[i] = x % 10; - x /= 10; - i++; - } - - int s = 0; - for(i = len - 1; i >=0 ; i--) - s += y[i] * Math.pow(10, len - 1 - i); - - return s; - } +public class Solution { + public int reverse(int x) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if(x == 0) return 0; + if(x < 0) return -reverse(-x); + + int len = (int)Math.log10(x) + 1; + int[] y = new int[len]; + + int i = 0; + while(i < len){ + y[i] = x % 10; + x /= 10; + i++; + } + + int s = 0; + for(i = len - 1; i >=0 ; i--) + s += y[i] * Math.pow(10, len - 1 - i); + + return s; + } } \ No newline at end of file diff --git a/reverse-linked-list-ii/Solution.java b/reverse-linked-list-ii/Solution.java index 8c4db87..519f910 100644 --- a/reverse-linked-list-ii/Solution.java +++ b/reverse-linked-list-ii/Solution.java @@ -1,64 +1,64 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseBetween(ListNode head, int m, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int c = 1; - - final ListNode _head = head; - - ListNode prev = null; - - ListNode jointLeft = null; - ListNode jointRight = null; - - while(head != null){ - - ListNode t = head.next; - - if(c == m){ - jointLeft = prev; - jointRight = head; - } - - if(c >= m && c <= n){ - head.next = prev; - } - - prev = head; - head = t; - - if(c == n){ - if(jointLeft != null){ - jointLeft.next = prev; - } - jointRight.next = head; - - if(jointRight == _head){ - return prev; - }else{ - return _head; - } - } - - c++; - - } - - return _head; - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode reverseBetween(ListNode head, int m, int n) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(head == null) return null; + if(head.next == null) return head; + + int c = 1; + + final ListNode _head = head; + + ListNode prev = null; + + ListNode jointLeft = null; + ListNode jointRight = null; + + while(head != null){ + + ListNode t = head.next; + + if(c == m){ + jointLeft = prev; + jointRight = head; + } + + if(c >= m && c <= n){ + head.next = prev; + } + + prev = head; + head = t; + + if(c == n){ + if(jointLeft != null){ + jointLeft.next = prev; + } + jointRight.next = head; + + if(jointRight == _head){ + return prev; + }else{ + return _head; + } + } + + c++; + + } + + return _head; + } } \ No newline at end of file diff --git a/reverse-nodes-in-k-group/Solution.java b/reverse-nodes-in-k-group/Solution.java index c9330fc..739b608 100644 --- a/reverse-nodes-in-k-group/Solution.java +++ b/reverse-nodes-in-k-group/Solution.java @@ -1,57 +1,57 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseKGroup(ListNode head, int k) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(k <= 1) return head; - - if(head == null) return null; - if(head.next == null) return head; - - ListNode tail = head; - ListNode prev = null; - - for(int i = 0; i < k ; i++){ - if(head == null){ - - // rollback - head = prev; - prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - tail.next = reverseKGroup(head, k); - - return prev; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if(k <= 1) return head; + + if(head == null) return null; + if(head.next == null) return head; + + ListNode tail = head; + ListNode prev = null; + + for(int i = 0; i < k ; i++){ + if(head == null){ + + // rollback + head = prev; + prev = null; + + while(head != null){ + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + tail.next = reverseKGroup(head, k); + + return prev; + + } } \ No newline at end of file diff --git a/reverse-words-in-a-string/Solution.java b/reverse-words-in-a-string/Solution.java index 4e61b34..b760659 100644 --- a/reverse-words-in-a-string/Solution.java +++ b/reverse-words-in-a-string/Solution.java @@ -1,35 +1,35 @@ -public class Solution { - public String reverseWords(String s) { - if(s == null) return null; - - - ArrayList words = new ArrayList(); - - StringBuilder buff = new StringBuilder(); - - for(char c : (s + " ").toCharArray()){ - if (c != ' '){ - buff.append(c); - }else{ - String w = buff.toString(); - if(!"".equals(w)){ - words.add(w); - buff = new StringBuilder(); - } - } - } - - if(words.size() == 0) return ""; - - buff = new StringBuilder(); - for(int i = words.size() - 1; i >0 ; i--){ - buff.append(words.get(i)); - buff.append(' '); - } - - buff.append(words.get(0)); - - return buff.toString(); - - } +public class Solution { + public String reverseWords(String s) { + if(s == null) return null; + + + ArrayList words = new ArrayList(); + + StringBuilder buff = new StringBuilder(); + + for(char c : (s + " ").toCharArray()){ + if (c != ' '){ + buff.append(c); + }else{ + String w = buff.toString(); + if(!"".equals(w)){ + words.add(w); + buff = new StringBuilder(); + } + } + } + + if(words.size() == 0) return ""; + + buff = new StringBuilder(); + for(int i = words.size() - 1; i >0 ; i--){ + buff.append(words.get(i)); + buff.append(' '); + } + + buff.append(words.get(0)); + + return buff.toString(); + + } } \ No newline at end of file diff --git a/roman-to-integer/Solution.java b/roman-to-integer/Solution.java index a059b41..de87539 100644 --- a/roman-to-integer/Solution.java +++ b/roman-to-integer/Solution.java @@ -1,55 +1,55 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - int index(char c){ - for(int i = 0 ; i < C.length; i++){ - if (C[i] == c) - return i; - } - - return -1; - } - - int rtoi(char c){ - return N[index(c)]; - } - - public int romanToInt(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s.length() <= 0) return 0; - - char[] cs = s.toCharArray(); - - int sum = rtoi(cs[0]); - - for (int i = 1 ; i < cs.length; i++){ - sum += rtoi(cs[i]); - - int j = i - 1; - int ci = index(cs[i]); - - while(j>=0 && index(cs[j]) < ci){ - sum -= rtoi(cs[j--]) * 2; - } - } - - - return sum; - } +public class Solution { + + /* + http://en.wikipedia.org/wiki/Roman_numerals + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1,000 + + to avoid four characters being repeated in succession + */ + + static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; + static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; + + int index(char c){ + for(int i = 0 ; i < C.length; i++){ + if (C[i] == c) + return i; + } + + return -1; + } + + int rtoi(char c){ + return N[index(c)]; + } + + public int romanToInt(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(s.length() <= 0) return 0; + + char[] cs = s.toCharArray(); + + int sum = rtoi(cs[0]); + + for (int i = 1 ; i < cs.length; i++){ + sum += rtoi(cs[i]); + + int j = i - 1; + int ci = index(cs[i]); + + while(j>=0 && index(cs[j]) < ci){ + sum -= rtoi(cs[j--]) * 2; + } + } + + + return sum; + } } \ No newline at end of file diff --git a/rotate-image/Solution.java b/rotate-image/Solution.java index 221b2ef..f35fecd 100644 --- a/rotate-image/Solution.java +++ b/rotate-image/Solution.java @@ -1,38 +1,38 @@ -public class Solution { - public void rotate(int[][] matrix) { - - - final int mx = matrix.length; - final int my = matrix[0].length; - int x,y; - - int t; - - int _my = my - 1; - for(x = 0; x < mx - 1; x++){ - for(y = 0; y < _my; y++){ - int ny = mx - 1 - x; - int nx = my - 1 - y; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - - } - _my--; - } - - - for(x = 0; x < mx ; x++){ - for(y = 0 ; y < my / 2; y++){ - int ny = my - 1 - y; - int nx = x; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - } - } - - } +public class Solution { + public void rotate(int[][] matrix) { + + + final int mx = matrix.length; + final int my = matrix[0].length; + int x,y; + + int t; + + int _my = my - 1; + for(x = 0; x < mx - 1; x++){ + for(y = 0; y < _my; y++){ + int ny = mx - 1 - x; + int nx = my - 1 - y; + + t = matrix[y][x]; + matrix[y][x] = matrix[ny][nx]; + matrix[ny][nx] = t; + + } + _my--; + } + + + for(x = 0; x < mx ; x++){ + for(y = 0 ; y < my / 2; y++){ + int ny = my - 1 - y; + int nx = x; + + t = matrix[y][x]; + matrix[y][x] = matrix[ny][nx]; + matrix[ny][nx] = t; + } + } + + } } \ No newline at end of file diff --git a/rotate-list/Solution.java b/rotate-list/Solution.java index a5081c6..efb2005 100644 --- a/rotate-list/Solution.java +++ b/rotate-list/Solution.java @@ -1,41 +1,41 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode rotateRight(ListNode head, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - ListNode _head = head; - - ListNode node = head; - int len = 1; - while(node.next != null){ - len++; - node = node.next; - } - - n %= len; - - ListNode tail = node; - - node = head; - for(int i = 0; i < len - n - 1; i++) node = node.next; - - tail.next = head; - ListNode rt = node.next; - node.next = null; - - return rt; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode rotateRight(ListNode head, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(head == null) return null; + + ListNode _head = head; + + ListNode node = head; + int len = 1; + while(node.next != null){ + len++; + node = node.next; + } + + n %= len; + + ListNode tail = node; + + node = head; + for(int i = 0; i < len - n - 1; i++) node = node.next; + + tail.next = head; + ListNode rt = node.next; + node.next = null; + + return rt; + + } } \ No newline at end of file diff --git a/same-tree/Solution.java b/same-tree/Solution.java index 602741d..a5806c2 100644 --- a/same-tree/Solution.java +++ b/same-tree/Solution.java @@ -1,21 +1,21 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - - if(p == null && q == null){ - return true; - }else if(p == null || q == null){ - return false; - } - - return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + + if(p == null && q == null){ + return true; + }else if(p == null || q == null){ + return false; + } + + return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } } \ No newline at end of file diff --git a/scramble-string/Solution.java b/scramble-string/Solution.java index 0ee6504..7323b3c 100644 --- a/scramble-string/Solution.java +++ b/scramble-string/Solution.java @@ -1,173 +1,173 @@ -public class Solution { - - static class Board { - - HashMap left = new HashMap(); - HashMap right = new HashMap(); - - String leftString; - String rightString; - - HashMap part(int idx){ - if(idx < left.size()){ - return left; - } else { - return right; - } - - } - - void add(Map m, Character c){ - Integer cnt = m.get(c); - - if(cnt == null){ - m.put(c, 1); - return; - } - - m.put(c, cnt + 1); - - } - - void addLeft(Character c){ - add(left, c); - } - - void addRight(Character c){ - add(right, c); - } - - int count(Map m, Character c){ - Integer cnt = m.get(c); - if(cnt == null) return 0; - - return cnt; - } - - boolean hasChar(int idx, Character c, int count){ - - HashMap m = part(idx); - - if(m == left){ - return count(m, c) >= count; - } - - return count(left, c) + count(right, c) >= count; - } - } - - List buildTwo(char[] all, int p){ - - Board b = new Board(); - - StringBuilder leftString = new StringBuilder(); - StringBuilder rightString = new StringBuilder(); - - for(int i = 0; i < all.length; i++){ - - Character c = all[i]; - if(i < p){ - leftString.append(c); - b.addLeft(c); - }else{ - rightString.append(c); - b.addRight(c); - } - } - - b.leftString = leftString.toString(); - b.rightString = rightString.toString(); - - Board mb = new Board(); - mb.left = new HashMap(b.right); - mb.right = new HashMap(b.left); - - mb.leftString = b.rightString; - mb.rightString = b.leftString; - - return Arrays.asList(new Board[]{b, mb}); - } - - boolean checkSameChar(char[] s1, char[] s2){ - s1 = Arrays.copyOf(s1, s1.length); - s2 = Arrays.copyOf(s2, s2.length); - - Arrays.sort(s1); - Arrays.sort(s2); - return Arrays.equals(s1, s2); - } - - static final Board SEP = new Board(); - - public boolean isScramble(String s1, String s2) { - - char[] _s1 = s1.toCharArray(); - char[] _s2 = s2.toCharArray(); - - if(_s1.length != _s2.length) - return false; - - if(_s1.length == 0) return true; - if(_s1.length == 1) return _s1[0] == _s2[0]; - if(!checkSameChar(_s1, _s2)) - return false; - - - LinkedList exp = new LinkedList(); - - for(int i = 1; i < _s1.length; i++){ - exp.addAll(buildTwo(_s1, i)); - } - - exp.add(SEP); - - HashMap counting = new HashMap(); - - for(int i = 0; i < _s2.length; i++){ - - Character c = _s2[i]; - - Integer cnt = counting.get(c); - - if(cnt == null){ - cnt = 0; - counting.put(c, 1); - }else{ - counting.put(c, cnt + 1); - } - - while(true){ - Board b = exp.poll(); - - if(b == SEP){ - if(exp.isEmpty()) - return false; - - exp.add(SEP); - break; - } - - if(b.hasChar(i, c, cnt + 1)){ - exp.add(b); - } - - } - - } - - for(Board b : exp){ - if(b != SEP){ - - if(isScramble(b.leftString , s2.substring(0, b.leftString.length()) ) - && isScramble(b.rightString, s2.substring(b.leftString.length()))) { - return true; - } - - } - } - - return false; - - } - +public class Solution { + + static class Board { + + HashMap left = new HashMap(); + HashMap right = new HashMap(); + + String leftString; + String rightString; + + HashMap part(int idx){ + if(idx < left.size()){ + return left; + } else { + return right; + } + + } + + void add(Map m, Character c){ + Integer cnt = m.get(c); + + if(cnt == null){ + m.put(c, 1); + return; + } + + m.put(c, cnt + 1); + + } + + void addLeft(Character c){ + add(left, c); + } + + void addRight(Character c){ + add(right, c); + } + + int count(Map m, Character c){ + Integer cnt = m.get(c); + if(cnt == null) return 0; + + return cnt; + } + + boolean hasChar(int idx, Character c, int count){ + + HashMap m = part(idx); + + if(m == left){ + return count(m, c) >= count; + } + + return count(left, c) + count(right, c) >= count; + } + } + + List buildTwo(char[] all, int p){ + + Board b = new Board(); + + StringBuilder leftString = new StringBuilder(); + StringBuilder rightString = new StringBuilder(); + + for(int i = 0; i < all.length; i++){ + + Character c = all[i]; + if(i < p){ + leftString.append(c); + b.addLeft(c); + }else{ + rightString.append(c); + b.addRight(c); + } + } + + b.leftString = leftString.toString(); + b.rightString = rightString.toString(); + + Board mb = new Board(); + mb.left = new HashMap(b.right); + mb.right = new HashMap(b.left); + + mb.leftString = b.rightString; + mb.rightString = b.leftString; + + return Arrays.asList(new Board[]{b, mb}); + } + + boolean checkSameChar(char[] s1, char[] s2){ + s1 = Arrays.copyOf(s1, s1.length); + s2 = Arrays.copyOf(s2, s2.length); + + Arrays.sort(s1); + Arrays.sort(s2); + return Arrays.equals(s1, s2); + } + + static final Board SEP = new Board(); + + public boolean isScramble(String s1, String s2) { + + char[] _s1 = s1.toCharArray(); + char[] _s2 = s2.toCharArray(); + + if(_s1.length != _s2.length) + return false; + + if(_s1.length == 0) return true; + if(_s1.length == 1) return _s1[0] == _s2[0]; + if(!checkSameChar(_s1, _s2)) + return false; + + + LinkedList exp = new LinkedList(); + + for(int i = 1; i < _s1.length; i++){ + exp.addAll(buildTwo(_s1, i)); + } + + exp.add(SEP); + + HashMap counting = new HashMap(); + + for(int i = 0; i < _s2.length; i++){ + + Character c = _s2[i]; + + Integer cnt = counting.get(c); + + if(cnt == null){ + cnt = 0; + counting.put(c, 1); + }else{ + counting.put(c, cnt + 1); + } + + while(true){ + Board b = exp.poll(); + + if(b == SEP){ + if(exp.isEmpty()) + return false; + + exp.add(SEP); + break; + } + + if(b.hasChar(i, c, cnt + 1)){ + exp.add(b); + } + + } + + } + + for(Board b : exp){ + if(b != SEP){ + + if(isScramble(b.leftString , s2.substring(0, b.leftString.length()) ) + && isScramble(b.rightString, s2.substring(b.leftString.length()))) { + return true; + } + + } + } + + return false; + + } + } \ No newline at end of file diff --git a/search-a-2d-matrix/Solution.java b/search-a-2d-matrix/Solution.java index 2acf68e..f40c863 100644 --- a/search-a-2d-matrix/Solution.java +++ b/search-a-2d-matrix/Solution.java @@ -1,30 +1,30 @@ -public class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = matrix.length; - int my = matrix[0].length; - - final int count = mx * my; - - int l = 0, r = count; - - while(l < r){ - int m = (r + l) / 2; - - int x = m / my; - int y = m % my; - - if(matrix[x][y] == target) - return true; - else if(matrix[x][y] < target) - l = m + 1; - else - r = m; - - - } - - return false; - } +public class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int mx = matrix.length; + int my = matrix[0].length; + + final int count = mx * my; + + int l = 0, r = count; + + while(l < r){ + int m = (r + l) / 2; + + int x = m / my; + int y = m % my; + + if(matrix[x][y] == target) + return true; + else if(matrix[x][y] < target) + l = m + 1; + else + r = m; + + + } + + return false; + } } \ No newline at end of file diff --git a/search-for-a-range/Solution.java b/search-for-a-range/Solution.java index 72156a8..01bd046 100644 --- a/search-for-a-range/Solution.java +++ b/search-for-a-range/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - public int[] searchRange(int[] A, int target) { - - int s = 0, e = A.length; - - while( s < e ){ - int mid = (s + e) / 2; - - if(A[mid] == target){ - - int _s = mid, _e = mid; - - while(_s - 1 >= 0 && A[_s - 1] == target) _s--; - while(_e + 1 < A.length && A[_e + 1] == target) _e++; - - return new int[]{_s, _e}; - - }else if(A[mid] < target){ - s = mid + 1; - }else if(A[mid] > target){ - e = mid; - } - - } - - return new int[]{-1, -1}; - - } +public class Solution { + public int[] searchRange(int[] A, int target) { + + int s = 0, e = A.length; + + while( s < e ){ + int mid = (s + e) / 2; + + if(A[mid] == target){ + + int _s = mid, _e = mid; + + while(_s - 1 >= 0 && A[_s - 1] == target) _s--; + while(_e + 1 < A.length && A[_e + 1] == target) _e++; + + return new int[]{_s, _e}; + + }else if(A[mid] < target){ + s = mid + 1; + }else if(A[mid] > target){ + e = mid; + } + + } + + return new int[]{-1, -1}; + + } } \ No newline at end of file diff --git a/search-in-rotated-sorted-array-ii/Solution.java b/search-in-rotated-sorted-array-ii/Solution.java index 269b8da..fea9221 100644 --- a/search-in-rotated-sorted-array-ii/Solution.java +++ b/search-in-rotated-sorted-array-ii/Solution.java @@ -1,60 +1,60 @@ -public class Solution { - public boolean search(int[] A, int target) { - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return true; - } - - if(target < A[mid]){ - // normal in first half - if (A[s] == A[mid]) { - if(A[mid] == A[e - 1]){ - // special - - s++; - e--; - - }else{ - s = mid + 1; - } - - } else if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - if (A[mid] == A[e - 1]) { - if(A[s] == A[mid]){ - s++; - e--; - }else{ - e = mid; - } - - - } else if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return false; - } +public class Solution { + public boolean search(int[] A, int target) { + int s = 0; + int e = A.length; + + while(s < e){ + int mid = (s + e) /2; + + if(A[mid] == target){ + return true; + } + + if(target < A[mid]){ + // normal in first half + if (A[s] == A[mid]) { + if(A[mid] == A[e - 1]){ + // special + + s++; + e--; + + }else{ + s = mid + 1; + } + + } else if(A[s] <= A[mid] && A[s] <= target){ + e = mid; + // abnormal + }else if(A[mid] <= A[e - 1]){ + e = mid; + }else { + s = mid + 1; + } + + } else { + + // normal in last half + if (A[mid] == A[e - 1]) { + if(A[s] == A[mid]){ + s++; + e--; + }else{ + e = mid; + } + + + } else if(A[mid] <= A[e - 1] && target <= A[e - 1]){ + s = mid + 1; + } else if(A[s] <= A[mid]) { + s = mid + 1; + } else { + e = mid; + } + + } + } + + return false; + } } \ No newline at end of file diff --git a/search-in-rotated-sorted-array/Solution.java b/search-in-rotated-sorted-array/Solution.java index cd47ebd..b185f3c 100644 --- a/search-in-rotated-sorted-array/Solution.java +++ b/search-in-rotated-sorted-array/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int search(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return mid; - } - - if(target < A[mid]){ - // normal in first half - - if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - - if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return -1; - } +public class Solution { + public int search(int[] A, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + int s = 0; + int e = A.length; + + while(s < e){ + int mid = (s + e) /2; + + if(A[mid] == target){ + return mid; + } + + if(target < A[mid]){ + // normal in first half + + if(A[s] <= A[mid] && A[s] <= target){ + e = mid; + // abnormal + }else if(A[mid] <= A[e - 1]){ + e = mid; + }else { + s = mid + 1; + } + + } else { + + // normal in last half + + if(A[mid] <= A[e - 1] && target <= A[e - 1]){ + s = mid + 1; + } else if(A[s] <= A[mid]) { + s = mid + 1; + } else { + e = mid; + } + + } + } + + return -1; + } } \ No newline at end of file diff --git a/search-insert-position/Solution.java b/search-insert-position/Solution.java index 86d9b2a..a47f99b 100644 --- a/search-insert-position/Solution.java +++ b/search-insert-position/Solution.java @@ -1,9 +1,9 @@ -public class Solution { - public int searchInsert(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - for(int i = 0; i < A.length; i++){ - if(A[i] >= target) return i; - } - return A.length; - } +public class Solution { + public int searchInsert(int[] A, int target) { + // Note: The Solution object is instantiated only once and is reused by each test case. + for(int i = 0; i < A.length; i++){ + if(A[i] >= target) return i; + } + return A.length; + } } \ No newline at end of file diff --git a/set-matrix-zeroes/Solution.java b/set-matrix-zeroes/Solution.java index 0d0969b..09d5995 100644 --- a/set-matrix-zeroes/Solution.java +++ b/set-matrix-zeroes/Solution.java @@ -1,65 +1,65 @@ -public class Solution { - public void setZeroes(int[][] matrix) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(matrix == null) return; - int mx = matrix.length; - if ( mx == 0) return; - int my = matrix[0].length; - - int x, y; - - boolean xfz = false, yfz = false; - - for(x = 0; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - xfz = true; - break; - } - } - - for(y = 0; y < my ; y++ ){ - if(matrix[0][y] == 0){ - yfz = true; - break; - } - } - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my ; y++){ - if(matrix[x][y] == 0){ - matrix[x][0] = 0; - matrix[0][y] = 0; - } - } - } - - for(x = 1; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - for(y = 0; y < my; y++){ - matrix[x][y] = 0; - } - } - } - - for(y = 1; y < my ; y++ ){ - if(matrix[0][y] == 0){ - for(x = 0; x < mx; x++){ - matrix[x][y] = 0; - } - } - } - - if(xfz){ - for(x = 0; x < mx ; x++ ){ - matrix[x][0] = 0; - } - } - - if(yfz){ - for(y = 0; y < my ; y++ ){ - matrix[0][y] = 0; - } - } - } +public class Solution { + public void setZeroes(int[][] matrix) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(matrix == null) return; + int mx = matrix.length; + if ( mx == 0) return; + int my = matrix[0].length; + + int x, y; + + boolean xfz = false, yfz = false; + + for(x = 0; x < mx ; x++ ){ + if(matrix[x][0] == 0){ + xfz = true; + break; + } + } + + for(y = 0; y < my ; y++ ){ + if(matrix[0][y] == 0){ + yfz = true; + break; + } + } + + for(x = 1; x < mx ; x++){ + for(y = 1; y < my ; y++){ + if(matrix[x][y] == 0){ + matrix[x][0] = 0; + matrix[0][y] = 0; + } + } + } + + for(x = 1; x < mx ; x++ ){ + if(matrix[x][0] == 0){ + for(y = 0; y < my; y++){ + matrix[x][y] = 0; + } + } + } + + for(y = 1; y < my ; y++ ){ + if(matrix[0][y] == 0){ + for(x = 0; x < mx; x++){ + matrix[x][y] = 0; + } + } + } + + if(xfz){ + for(x = 0; x < mx ; x++ ){ + matrix[x][0] = 0; + } + } + + if(yfz){ + for(y = 0; y < my ; y++ ){ + matrix[0][y] = 0; + } + } + } } \ No newline at end of file diff --git a/simplify-path/Solution.java b/simplify-path/Solution.java index 035b98d..fb04589 100644 --- a/simplify-path/Solution.java +++ b/simplify-path/Solution.java @@ -1,44 +1,44 @@ -public class Solution { - public String simplifyPath(String path) { - - String[] names = path.split("/"); - - int eat = 0; - - LinkedList stack = new LinkedList(); - - for(int i = names.length - 1; i >= 0; i--){ - - String token = names[i]; - - if("..".equals(token)){ - eat++; - }else if(".".equals(token)){ - // do nothing - }else if("".equals(token)){ - // do nothing - }else { - - // dir name - if(eat > 0){ - eat--; - }else{ - stack.push(token); - } - } - } - - StringBuilder s = new StringBuilder(); - - s.append("/"); - - while(stack.size() > 1){ - s.append(stack.pop()); - s.append("/"); - } - - if(!stack.isEmpty()) s.append(stack.pop()); - - return s.toString(); - } -} +public class Solution { + public String simplifyPath(String path) { + + String[] names = path.split("/"); + + int eat = 0; + + LinkedList stack = new LinkedList(); + + for(int i = names.length - 1; i >= 0; i--){ + + String token = names[i]; + + if("..".equals(token)){ + eat++; + }else if(".".equals(token)){ + // do nothing + }else if("".equals(token)){ + // do nothing + }else { + + // dir name + if(eat > 0){ + eat--; + }else{ + stack.push(token); + } + } + } + + StringBuilder s = new StringBuilder(); + + s.append("/"); + + while(stack.size() > 1){ + s.append(stack.pop()); + s.append("/"); + } + + if(!stack.isEmpty()) s.append(stack.pop()); + + return s.toString(); + } +} diff --git a/single-number-ii/Solution.java b/single-number-ii/Solution.java index df011a8..eae2915 100644 --- a/single-number-ii/Solution.java +++ b/single-number-ii/Solution.java @@ -1,32 +1,32 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[] count = new int[Integer.SIZE]; - int[] bit = new int[Integer.SIZE]; - - Arrays.fill(count, 0); - Arrays.fill(bit, 0); - - for(int a : A){ - - for(int b = 0; b < Integer.SIZE; b++){ - int x = a >>> b & 1; - bit[b] |= x; - - if(x == 1) - count[b]++; - } - - } - - int s = 0; - for(int b = 0; b < Integer.SIZE; b++ ){ - if (count[b] % 3 != 0) - s |= bit[b] << b; - } - - return s; - - } +public class Solution { + public int singleNumber(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int[] count = new int[Integer.SIZE]; + int[] bit = new int[Integer.SIZE]; + + Arrays.fill(count, 0); + Arrays.fill(bit, 0); + + for(int a : A){ + + for(int b = 0; b < Integer.SIZE; b++){ + int x = a >>> b & 1; + bit[b] |= x; + + if(x == 1) + count[b]++; + } + + } + + int s = 0; + for(int b = 0; b < Integer.SIZE; b++ ){ + if (count[b] % 3 != 0) + s |= bit[b] << b; + } + + return s; + + } } \ No newline at end of file diff --git a/single-number/Solution.java b/single-number/Solution.java index efdb0d3..5d80c1c 100644 --- a/single-number/Solution.java +++ b/single-number/Solution.java @@ -1,13 +1,13 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if (A.length == 1) return A[0]; - int s = A[0]; - - for(int i = 1; i< A.length; i++) - s ^= A[i]; - - return s; - - } +public class Solution { + public int singleNumber(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if (A.length == 1) return A[0]; + int s = A[0]; + + for(int i = 1; i< A.length; i++) + s ^= A[i]; + + return s; + + } } \ No newline at end of file diff --git a/sort-colors/Solution.java b/sort-colors/Solution.java index 2460bee..3749c0e 100644 --- a/sort-colors/Solution.java +++ b/sort-colors/Solution.java @@ -1,36 +1,36 @@ -public class Solution { - public void sortColors(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int red = 0; - int blue = A.length - 1; - - int p = 0; - - int t = 0; - - while(p <= blue){ - - if(A[p] == 0){ //red - t = A[p]; - A[p] = A[red]; - A[red] = t; - - red++; - p++; - - }else if(A[p] == 2){ // blue - t = A[p]; - A[p] = A[blue]; - A[blue] = t; - - blue--; - }else{ // white - - p++; - - } - - } - } +public class Solution { + public void sortColors(int[] A) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int red = 0; + int blue = A.length - 1; + + int p = 0; + + int t = 0; + + while(p <= blue){ + + if(A[p] == 0){ //red + t = A[p]; + A[p] = A[red]; + A[red] = t; + + red++; + p++; + + }else if(A[p] == 2){ // blue + t = A[p]; + A[p] = A[blue]; + A[blue] = t; + + blue--; + }else{ // white + + p++; + + } + + } + } } \ No newline at end of file diff --git a/sort-list/Solution.java b/sort-list/Solution.java index 6d942df..7407309 100644 --- a/sort-list/Solution.java +++ b/sort-list/Solution.java @@ -1,60 +1,60 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } - - - public ListNode sortList(ListNode head) { - if(head == null) return null; - if(head.next == null) return head; - - ListNode fast = head.next; - ListNode slow = head; - - while(fast != null && fast.next != null){ - slow = slow.next; - fast = fast.next.next; - } - - ListNode h2 = slow.next; - slow.next = null; - - return mergeTwoLists(sortList(head), sortList(h2)); - - - } +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + // Note: The Solution object is instantiated only once and is reused by each test case. + ListNode rt = new ListNode(0); + ListNode h = rt; + + while( l1 != null && l2 != null){ + if(l1.val < l2.val){ + rt.next = l1; + l1 = l1.next; + }else{ + rt.next = l2; + l2 = l2.next; + } + + rt = rt.next; + } + + if(l1 != null) rt.next = l1; + else rt.next = l2; + + + return h.next; + + + } + + + public ListNode sortList(ListNode head) { + if(head == null) return null; + if(head.next == null) return head; + + ListNode fast = head.next; + ListNode slow = head; + + while(fast != null && fast.next != null){ + slow = slow.next; + fast = fast.next.next; + } + + ListNode h2 = slow.next; + slow.next = null; + + return mergeTwoLists(sortList(head), sortList(h2)); + + + } } \ No newline at end of file diff --git a/spiral-matrix-ii/Solution.java b/spiral-matrix-ii/Solution.java index 0291cf1..0a30f2c 100644 --- a/spiral-matrix-ii/Solution.java +++ b/spiral-matrix-ii/Solution.java @@ -1,43 +1,43 @@ -public class Solution { - public int[][] generateMatrix(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[][] rt = new int[n][n]; - if(n <= 0) return rt; - - int c = 1; - - int x = 0, y = 0, my = n , mx = n; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my; i++){ - rt[y][i] = c++; - } - - y++; - - for(int i = y; i < my && x < mx ; i++ ){ - rt[i][mx - 1] = c++; - } - - mx--; - - for(int i = mx - 1; i >= x && y < my; i--){ - rt[my - 1][i] = c++; - } - - my--; - - for(int i = my - 1; i>= y && x < mx; i--){ - rt[i][x] = c++; - } - - x++; - - } - - return rt; - - - } +public class Solution { + public int[][] generateMatrix(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int[][] rt = new int[n][n]; + if(n <= 0) return rt; + + int c = 1; + + int x = 0, y = 0, my = n , mx = n; + + while(x < mx && y < my){ + for(int i = x; i < mx && y < my; i++){ + rt[y][i] = c++; + } + + y++; + + for(int i = y; i < my && x < mx ; i++ ){ + rt[i][mx - 1] = c++; + } + + mx--; + + for(int i = mx - 1; i >= x && y < my; i--){ + rt[my - 1][i] = c++; + } + + my--; + + for(int i = my - 1; i>= y && x < mx; i--){ + rt[i][x] = c++; + } + + x++; + + } + + return rt; + + + } } \ No newline at end of file diff --git a/spiral-matrix/Solution.java b/spiral-matrix/Solution.java index ea8a38d..e4dc0ba 100644 --- a/spiral-matrix/Solution.java +++ b/spiral-matrix/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public List spiralOrder(int[][] matrix) { - ArrayList rt = new ArrayList(); - - if(matrix.length == 0) return rt; - - int x = 0, y = 0, my = matrix.length, mx = matrix[0].length; - //int dx = 1, dy = 1; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my ; i++){ - rt.add(matrix[y][i]); - } - - y++; - - for(int i = y; i< my && x < mx; i++){ - rt.add(matrix[i][mx - 1]); - } - - mx--; - - for(int i = mx - 1; i >= x && y < my ; i--){ - rt.add(matrix[my - 1][i]); - } - - my--; - - for(int i = my - 1; i >= y && x < mx; i--){ - rt.add(matrix[i][x]); - } - - x++; - - } - - - return rt; - - } -} +public class Solution { + public List spiralOrder(int[][] matrix) { + ArrayList rt = new ArrayList(); + + if(matrix.length == 0) return rt; + + int x = 0, y = 0, my = matrix.length, mx = matrix[0].length; + //int dx = 1, dy = 1; + + while(x < mx && y < my){ + for(int i = x; i < mx && y < my ; i++){ + rt.add(matrix[y][i]); + } + + y++; + + for(int i = y; i< my && x < mx; i++){ + rt.add(matrix[i][mx - 1]); + } + + mx--; + + for(int i = mx - 1; i >= x && y < my ; i--){ + rt.add(matrix[my - 1][i]); + } + + my--; + + for(int i = my - 1; i >= y && x < mx; i--){ + rt.add(matrix[i][x]); + } + + x++; + + } + + + return rt; + + } +} diff --git a/sqrtx/Solution.java b/sqrtx/Solution.java index c1d7706..0fb77d9 100644 --- a/sqrtx/Solution.java +++ b/sqrtx/Solution.java @@ -1,41 +1,41 @@ -public class Solution { - public int sqrt(int x) { - - if(x < 0) return -1; - if(x == 0) return 0; - - int s = 0; - int e = x; - - - while(s < e){ - int m = (e - s) / 2 + s; - - int m1 = x / (m + 1); - int m2 = x / (m + 1 + 1); - - if(m + 1 == m1){ - return m + 1; - } - - if(m + 1 + 1 == m2){ - return m + 1 + 1; - } - - if(m + 1 < m1 && m2 < m + 1 + 1){ - return m + 1; - } - - - if(m1 < m + 1){ - e = m; - }else{ - s = m + 1; - } - - } - - - throw new RuntimeException(); - } -} +public class Solution { + public int sqrt(int x) { + + if(x < 0) return -1; + if(x == 0) return 0; + + int s = 0; + int e = x; + + + while(s < e){ + int m = (e - s) / 2 + s; + + int m1 = x / (m + 1); + int m2 = x / (m + 1 + 1); + + if(m + 1 == m1){ + return m + 1; + } + + if(m + 1 + 1 == m2){ + return m + 1 + 1; + } + + if(m + 1 < m1 && m2 < m + 1 + 1){ + return m + 1; + } + + + if(m1 < m + 1){ + e = m; + }else{ + s = m + 1; + } + + } + + + throw new RuntimeException(); + } +} diff --git a/string-to-integer-atoi/Solution.java b/string-to-integer-atoi/Solution.java index 0211ce2..53baea7 100644 --- a/string-to-integer-atoi/Solution.java +++ b/string-to-integer-atoi/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - public int atoi(String str) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - // null "" - if (str == null || "".equals(str)) - return 0; - - char[] ds = str.toCharArray(); - - int sum = 0; - - int sign = 1; - - int s = 0; - - boolean signseen = false; - - while(s < ds.length && !('0' <= ds[s] && ds[s] <= '9')){ - - if(signseen) - return 0; - - - - if(ds[s] == '-'){ - sign *= -1; - signseen = true; - }else if(ds[s] == '+'){ - signseen = true; - }else if(ds[s] != ' '){ - return 0; - } - - s++; - } - - int e = s; - while(e < ds.length && ('0' <= ds[e] && ds[e] <= '9')){ - e++; - } - - int p = 0; - - boolean flago = false; - for(int i = s; i < e ; i++){ - - if(sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && ds[i] - '0' > Integer.MAX_VALUE % 10 )) - flago = true; - - sum = sum * 10 + (ds[i] - '0'); - } - - if (flago) - if(sign > 0) - return Integer.MAX_VALUE; - else - return Integer.MIN_VALUE; - - return sum * sign; - - } +public class Solution { + public int atoi(String str) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + + // null "" + if (str == null || "".equals(str)) + return 0; + + char[] ds = str.toCharArray(); + + int sum = 0; + + int sign = 1; + + int s = 0; + + boolean signseen = false; + + while(s < ds.length && !('0' <= ds[s] && ds[s] <= '9')){ + + if(signseen) + return 0; + + + + if(ds[s] == '-'){ + sign *= -1; + signseen = true; + }else if(ds[s] == '+'){ + signseen = true; + }else if(ds[s] != ' '){ + return 0; + } + + s++; + } + + int e = s; + while(e < ds.length && ('0' <= ds[e] && ds[e] <= '9')){ + e++; + } + + int p = 0; + + boolean flago = false; + for(int i = s; i < e ; i++){ + + if(sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && ds[i] - '0' > Integer.MAX_VALUE % 10 )) + flago = true; + + sum = sum * 10 + (ds[i] - '0'); + } + + if (flago) + if(sign > 0) + return Integer.MAX_VALUE; + else + return Integer.MIN_VALUE; + + return sum * sign; + + } } \ No newline at end of file diff --git a/subsets-ii/Solution.java b/subsets-ii/Solution.java index 7e674b2..676423c 100644 --- a/subsets-ii/Solution.java +++ b/subsets-ii/Solution.java @@ -1,49 +1,49 @@ -public class Solution { - public List> subsetsWithDup(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if (num.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(num); - - long mask = (long) Math.pow(2, num.length); - - next: - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < num.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(num[(int)j]); - } - } - - next_lv: - for(List _level : rt){ - - if(_level.size() == level.size()){ - for(int li = 0; li < _level.size(); li++){ - if(!_level.get(li).equals(level.get(li))) - continue next_lv; - } - - continue next; - } - } - rt.add(level); - - } - - return rt; - - } -} +public class Solution { + public List> subsetsWithDup(int[] num) { + + ArrayList> rt = new ArrayList>(); + + if (num.length == 0){ + rt.add(new ArrayList()); + + return rt; + } + + Arrays.sort(num); + + long mask = (long) Math.pow(2, num.length); + + next: + for(long i = 0; i < mask; i++){ + + ArrayList level = new ArrayList(); + + for(long j = 0; j < num.length; j++){ + + long x = (long) Math.pow(2, j); + + if((x & i) == x){ + level.add(num[(int)j]); + } + } + + next_lv: + for(List _level : rt){ + + if(_level.size() == level.size()){ + for(int li = 0; li < _level.size(); li++){ + if(!_level.get(li).equals(level.get(li))) + continue next_lv; + } + + continue next; + } + } + rt.add(level); + + } + + return rt; + + } +} diff --git a/subsets/Solution.java b/subsets/Solution.java index a6e54ca..f75027a 100644 --- a/subsets/Solution.java +++ b/subsets/Solution.java @@ -1,34 +1,34 @@ -public class Solution { - public List> subsets(int[] S) { - ArrayList> rt = new ArrayList>(); - - if (S.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(S); - - long mask = (long) Math.pow(2, S.length); - - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < S.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(S[(int)j]); - } - } - - rt.add(level); - - } - - return rt; - } -} +public class Solution { + public List> subsets(int[] S) { + ArrayList> rt = new ArrayList>(); + + if (S.length == 0){ + rt.add(new ArrayList()); + + return rt; + } + + Arrays.sort(S); + + long mask = (long) Math.pow(2, S.length); + + for(long i = 0; i < mask; i++){ + + ArrayList level = new ArrayList(); + + for(long j = 0; j < S.length; j++){ + + long x = (long) Math.pow(2, j); + + if((x & i) == x){ + level.add(S[(int)j]); + } + } + + rt.add(level); + + } + + return rt; + } +} diff --git a/substring-with-concatenation-of-all-words/Solution.java b/substring-with-concatenation-of-all-words/Solution.java index 8c74730..cc4f943 100644 --- a/substring-with-concatenation-of-all-words/Solution.java +++ b/substring-with-concatenation-of-all-words/Solution.java @@ -1,61 +1,61 @@ -public class Solution { - - boolean checkCat(String s, HashMap lm, int wordLen){ - - while(s.length() > 0){ - String w = s.substring(0, wordLen); - - Integer v = lm.get(w); - - if(v == null) return false; - if(v == 0) return false; - - s = s.substring(wordLen); - - v--; - lm.put(w, v); - } - - - return true; - } - - public List findSubstring(String S, String[] L) { - - if(L.length == 0) return new ArrayList(); - - ArrayList rt = new ArrayList(); - - - HashMap lm = new HashMap(); - - for(String l : L){ - - Integer v = lm.get(l); - - if(v == null) v = 0; - v++; - - lm.put(l, v); - } - - - final int wordLen = L[0].length(); - - for(int i = 0; i + wordLen <= S.length(); i++){ - - if(lm.containsKey(S.substring(i, i + wordLen))){ - - if(i + wordLen * L.length > S.length()){ - break; - } - - if(checkCat(S.substring(i, i + wordLen * L.length), new HashMap(lm), wordLen)){ - rt.add(i); - } - } - } - - return rt; - } +public class Solution { + + boolean checkCat(String s, HashMap lm, int wordLen){ + + while(s.length() > 0){ + String w = s.substring(0, wordLen); + + Integer v = lm.get(w); + + if(v == null) return false; + if(v == 0) return false; + + s = s.substring(wordLen); + + v--; + lm.put(w, v); + } + + + return true; + } + + public List findSubstring(String S, String[] L) { + + if(L.length == 0) return new ArrayList(); + + ArrayList rt = new ArrayList(); + + + HashMap lm = new HashMap(); + + for(String l : L){ + + Integer v = lm.get(l); + + if(v == null) v = 0; + v++; + + lm.put(l, v); + } + + + final int wordLen = L[0].length(); + + for(int i = 0; i + wordLen <= S.length(); i++){ + + if(lm.containsKey(S.substring(i, i + wordLen))){ + + if(i + wordLen * L.length > S.length()){ + break; + } + + if(checkCat(S.substring(i, i + wordLen * L.length), new HashMap(lm), wordLen)){ + rt.add(i); + } + } + } + + return rt; + } } \ No newline at end of file diff --git a/sudoku-solver/Solution.java b/sudoku-solver/Solution.java index 3431bff..62e3c4f 100644 --- a/sudoku-solver/Solution.java +++ b/sudoku-solver/Solution.java @@ -1,117 +1,117 @@ -public class Solution { - - static final List VALID = Arrays.asList(new Character[]{ '1' , '2', '3', '4', '5', '6', '7', '8', '9'}); - - boolean _solveSudoku(char[][] board){ - int mx = board.length; - int my = board[0].length; - - int x ,y; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - - if(board[x][y] == '.'){ - int _x, _y; - HashSet val = new HashSet(VALID); - - for(_y = 0; _y < my; _y++) - val.remove(board[x][_y]); - - for(_x = 0; _x < mx; _x++) - val.remove(board[_x][y]); - - int sx = x / 3 * 3; - int sy = y / 3 * 3; - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - val.remove(board[sx + ox][sy + oy]); - } - - for(char c : val){ - board[x][y] = c; - - if(isValidSudoku(board)){ - // try next '.' - if(_solveSudoku(board)){ - return true; - } - - // try another number - } - - board[x][y] = '.'; - } - - // board[x][y] is '.' return false to fail fast - return false; - } - - - } - } - - return true; - } - - public void solveSudoku(char[][] board) { - _solveSudoku(board); - } - - boolean isValidSudoku(char[][] board) { - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } - -} +public class Solution { + + static final List VALID = Arrays.asList(new Character[]{ '1' , '2', '3', '4', '5', '6', '7', '8', '9'}); + + boolean _solveSudoku(char[][] board){ + int mx = board.length; + int my = board[0].length; + + int x ,y; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + + if(board[x][y] == '.'){ + int _x, _y; + HashSet val = new HashSet(VALID); + + for(_y = 0; _y < my; _y++) + val.remove(board[x][_y]); + + for(_x = 0; _x < mx; _x++) + val.remove(board[_x][y]); + + int sx = x / 3 * 3; + int sy = y / 3 * 3; + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + val.remove(board[sx + ox][sy + oy]); + } + + for(char c : val){ + board[x][y] = c; + + if(isValidSudoku(board)){ + // try next '.' + if(_solveSudoku(board)){ + return true; + } + + // try another number + } + + board[x][y] = '.'; + } + + // board[x][y] is '.' return false to fail fast + return false; + } + + + } + } + + return true; + } + + public void solveSudoku(char[][] board) { + _solveSudoku(board); + } + + boolean isValidSudoku(char[][] board) { + + int mx = board.length; + int my = board[0].length; + + int x, y; + + for(x = 0; x < mx; x++){ + HashSet col = new HashSet(); + for(y = 0; y < my; y++){ + char c = board[x][y]; + if(c != '.'){ + if(col.contains(c)) return false; + + col.add(c); + } + } + } + + for(y = 0; y < my; y++){ + HashSet row = new HashSet(); + for(x = 0; x < mx; x++){ + char c = board[x][y]; + if(c != '.'){ + if(row.contains(c)) return false; + + row.add(c); + } + } + } + + for(x = 0; x < mx; x += 3){ + for(y = 0; y < my; y += 3){ + + HashSet block = new HashSet(); + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + char c = board[x + ox][y + oy]; + if(c != '.'){ + if(block.contains(c)) return false; + + block.add(c); + } + } + } + } + + return true; + } + +} diff --git a/sum-root-to-leaf-numbers/Solution.java b/sum-root-to-leaf-numbers/Solution.java index 544717f..ce7fbfb 100644 --- a/sum-root-to-leaf-numbers/Solution.java +++ b/sum-root-to-leaf-numbers/Solution.java @@ -1,27 +1,27 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int sumNumbers(TreeNode root, int parentval){ - - if(root == null) return 0; - - int p = parentval * 10 + root.val; - - if(root.left == null && root.right == null) return p; - - return sumNumbers(root.left, p) + sumNumbers(root.right, p); - - } - - public int sumNumbers(TreeNode root) { - return sumNumbers(root, 0); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int sumNumbers(TreeNode root, int parentval){ + + if(root == null) return 0; + + int p = parentval * 10 + root.val; + + if(root.left == null && root.right == null) return p; + + return sumNumbers(root.left, p) + sumNumbers(root.right, p); + + } + + public int sumNumbers(TreeNode root) { + return sumNumbers(root, 0); + } +} diff --git a/surrounded-regions/Solution.java b/surrounded-regions/Solution.java index dd6ec02..c38a38b 100644 --- a/surrounded-regions/Solution.java +++ b/surrounded-regions/Solution.java @@ -1,101 +1,101 @@ -public class Solution { - - static class Point{ - int x; - int y; - - Point(int x, int y){ - this.x = x; - this.y = y; - } - } - - HashSet boarderConnected; - - String pointId(int x, int y){ - return x + "," + y; - } - - - // fuck stack - boolean connectIfNotConnected(char[][] board, int x, int y){ - - if(x < 0 || y < 0) return false; - if(x >= board.length || y >= board[0].length) return false; - - if(board[x][y] == 'X') return false; - - String id = pointId(x, y); - if(boarderConnected.contains(id)) return false; - - boarderConnected.add(id); - - return true; - } - - void connectBoarder(char[][] board, int x, int y){ - - - - //connectBoarder(board, x + 1, y); - //connectBoarder(board, x - 1, y); - //connectBoarder(board, x, y + 1); - //connectBoarder(board, x, y - 1); - - LinkedList queue = new LinkedList(); - - queue.add(new Point(x, y)); - - while(!queue.isEmpty()){ - Point p = queue.poll(); - - if(connectIfNotConnected(board, p.x, p.y)){ - - queue.add(new Point(p.x + 1, p.y)); - queue.add(new Point(p.x - 1, p.y)); - - queue.add(new Point(p.x, p.y + 1)); - queue.add(new Point(p.x, p.y - 1)); - } - - } - - } - - public void solve(char[][] board) { - - int mx = board.length; - if (mx < 3) return; - - int my = board[0].length; - if (my < 3) return; - - boarderConnected = new HashSet(); - - int x; - int y; - - for(x = 0; x < mx; x++){ - connectBoarder(board, x, 0); - connectBoarder(board, x, my - 1); - } - - for(y = 0; y < my; y++){ - connectBoarder(board, 0, y); - connectBoarder(board, mx - 1, y); - } - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if(board[x][y] == 'O'){ - if(!boarderConnected.contains(pointId(x, y))){ - board[x][y] = 'X'; - } - } - } - } - - - - } +public class Solution { + + static class Point{ + int x; + int y; + + Point(int x, int y){ + this.x = x; + this.y = y; + } + } + + HashSet boarderConnected; + + String pointId(int x, int y){ + return x + "," + y; + } + + + // fuck stack + boolean connectIfNotConnected(char[][] board, int x, int y){ + + if(x < 0 || y < 0) return false; + if(x >= board.length || y >= board[0].length) return false; + + if(board[x][y] == 'X') return false; + + String id = pointId(x, y); + if(boarderConnected.contains(id)) return false; + + boarderConnected.add(id); + + return true; + } + + void connectBoarder(char[][] board, int x, int y){ + + + + //connectBoarder(board, x + 1, y); + //connectBoarder(board, x - 1, y); + //connectBoarder(board, x, y + 1); + //connectBoarder(board, x, y - 1); + + LinkedList queue = new LinkedList(); + + queue.add(new Point(x, y)); + + while(!queue.isEmpty()){ + Point p = queue.poll(); + + if(connectIfNotConnected(board, p.x, p.y)){ + + queue.add(new Point(p.x + 1, p.y)); + queue.add(new Point(p.x - 1, p.y)); + + queue.add(new Point(p.x, p.y + 1)); + queue.add(new Point(p.x, p.y - 1)); + } + + } + + } + + public void solve(char[][] board) { + + int mx = board.length; + if (mx < 3) return; + + int my = board[0].length; + if (my < 3) return; + + boarderConnected = new HashSet(); + + int x; + int y; + + for(x = 0; x < mx; x++){ + connectBoarder(board, x, 0); + connectBoarder(board, x, my - 1); + } + + for(y = 0; y < my; y++){ + connectBoarder(board, 0, y); + connectBoarder(board, mx - 1, y); + } + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + if(board[x][y] == 'O'){ + if(!boarderConnected.contains(pointId(x, y))){ + board[x][y] = 'X'; + } + } + } + } + + + + } } \ No newline at end of file diff --git a/swap-nodes-in-pairs/Solution.java b/swap-nodes-in-pairs/Solution.java index 8cb96bd..3d1be6b 100644 --- a/swap-nodes-in-pairs/Solution.java +++ b/swap-nodes-in-pairs/Solution.java @@ -1,28 +1,28 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode swapPairs(ListNode head) { - - - if (head == null) return null; - - if (head.next == null) return head; - - ListNode newhead = head.next; - head.next = swapPairs(head.next.next); - - newhead.next = head; - - return newhead; - - } +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode swapPairs(ListNode head) { + + + if (head == null) return null; + + if (head.next == null) return head; + + ListNode newhead = head.next; + head.next = swapPairs(head.next.next); + + newhead.next = head; + + return newhead; + + } } \ No newline at end of file diff --git a/symmetric-tree/Solution.java b/symmetric-tree/Solution.java index 0d116e0..7c8ef60 100644 --- a/symmetric-tree/Solution.java +++ b/symmetric-tree/Solution.java @@ -1,75 +1,75 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeNode EMPTY = new TreeNode(0); - - TreeNode nullToEmpty(TreeNode node){ - if(node == null) return EMPTY; - - return node; - } - - - public boolean isSymmetric(TreeNode root) { - - if(root == null) return true; - - LinkedList queue = new LinkedList(); - final TreeNode END = new TreeNode(0); - - LinkedList level = new LinkedList(); - - level.add(nullToEmpty(root.left)); - level.add(nullToEmpty(root.right)); - - queue.add(END); - queue.add(nullToEmpty(root.left)); - queue.add(nullToEmpty(root.right)); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - - // check - while(!level.isEmpty()){ - TreeNode left = level.pollFirst(); - TreeNode right = level.pollLast(); - - if(left == right) continue; - - if(left == EMPTY && right != EMPTY) return false; - if(left != EMPTY && right == EMPTY) return false; - - if(left.val != right.val) return false; - - } - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node); - - if(node != EMPTY){ - queue.add(nullToEmpty(node.left)); - queue.add(nullToEmpty(node.right)); - } - } - - - } - - - return true; - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static final TreeNode EMPTY = new TreeNode(0); + + TreeNode nullToEmpty(TreeNode node){ + if(node == null) return EMPTY; + + return node; + } + + + public boolean isSymmetric(TreeNode root) { + + if(root == null) return true; + + LinkedList queue = new LinkedList(); + final TreeNode END = new TreeNode(0); + + LinkedList level = new LinkedList(); + + level.add(nullToEmpty(root.left)); + level.add(nullToEmpty(root.right)); + + queue.add(END); + queue.add(nullToEmpty(root.left)); + queue.add(nullToEmpty(root.right)); + + while(!queue.isEmpty()){ + + TreeNode node = queue.poll(); + + if(node == END){ + + // check + while(!level.isEmpty()){ + TreeNode left = level.pollFirst(); + TreeNode right = level.pollLast(); + + if(left == right) continue; + + if(left == EMPTY && right != EMPTY) return false; + if(left != EMPTY && right == EMPTY) return false; + + if(left.val != right.val) return false; + + } + + if(!queue.isEmpty()) queue.add(END); + + }else{ + + level.add(node); + + if(node != EMPTY){ + queue.add(nullToEmpty(node.left)); + queue.add(nullToEmpty(node.right)); + } + } + + + } + + + return true; + } +} diff --git a/text-justification/Solution.java b/text-justification/Solution.java index 05dbc84..e8a5f15 100644 --- a/text-justification/Solution.java +++ b/text-justification/Solution.java @@ -1,64 +1,64 @@ -public class Solution { - - String space(int len){ - char[] s = new char[len]; - Arrays.fill(s, ' '); - return new String(s); - } - - public List fullJustify(String[] words, int L) { - - ArrayList text = new ArrayList(); - - int p = 0; - int lastp = 0; - while(p < words.length){ - - if(L == 0 && "".equals(words[p])){ - text.add(""); - p++; - continue; - } - - int l = 0; - while(l < L && p < words.length){ - l += words[p++].length() + 1; - } - - if(l - 1 > L) l -= words[--p].length() + 1; - - int count = p - lastp; - int left = L - l + count; - - int add; - if(count == 1) add = left; - else if (p - 1 == words.length - 1) { add = 1; left = count - 1;} // fuck... - else add = left / ( count - 1); - - left -= add * (count - 1); - - String s = ""; - for(int i = lastp; i < p - 1; i++){ - if(left > 0){ - s += words[i] + space(add + 1); - left--; - }else{ - s += words[i] + space(add); - } - } - - left = L - s.length() - words[p - 1].length(); - - if(count == 1 || p - 1 == words.length - 1) // fuck... - s += words[p - 1] + space(left); - else - s += space(left) + words[p - 1]; - - text.add(s); - lastp = p; - } - - return text; - - } -} +public class Solution { + + String space(int len){ + char[] s = new char[len]; + Arrays.fill(s, ' '); + return new String(s); + } + + public List fullJustify(String[] words, int L) { + + ArrayList text = new ArrayList(); + + int p = 0; + int lastp = 0; + while(p < words.length){ + + if(L == 0 && "".equals(words[p])){ + text.add(""); + p++; + continue; + } + + int l = 0; + while(l < L && p < words.length){ + l += words[p++].length() + 1; + } + + if(l - 1 > L) l -= words[--p].length() + 1; + + int count = p - lastp; + int left = L - l + count; + + int add; + if(count == 1) add = left; + else if (p - 1 == words.length - 1) { add = 1; left = count - 1;} // fuck... + else add = left / ( count - 1); + + left -= add * (count - 1); + + String s = ""; + for(int i = lastp; i < p - 1; i++){ + if(left > 0){ + s += words[i] + space(add + 1); + left--; + }else{ + s += words[i] + space(add); + } + } + + left = L - s.length() - words[p - 1].length(); + + if(count == 1 || p - 1 == words.length - 1) // fuck... + s += words[p - 1] + space(left); + else + s += space(left) + words[p - 1]; + + text.add(s); + lastp = p; + } + + return text; + + } +} diff --git a/trapping-rain-water/Solution.java b/trapping-rain-water/Solution.java index c8ae754..1cf62dd 100644 --- a/trapping-rain-water/Solution.java +++ b/trapping-rain-water/Solution.java @@ -1,72 +1,72 @@ -public class Solution { - - static class Bar{ - int pos; - int height; - - Bar(int pos, int height){ - this.pos = pos; - this.height = height; - } - } - - int containWater(Deque queue){ - - Bar left = queue.peekFirst(); - Bar right = queue.peekLast(); - - int water = 0; - - if(right.height >= left.height){ - - water += Math.min(right.height, left.height) * (right.pos - left.pos - 1); - - queue.removeFirst(); // remove left - - // remove stones - while(queue.size() > 1){ - water -= queue.removeFirst().height; - } - } - - return water; - } - - int[] reverseAndToInt(Deque queue){ - int[] a = new int[queue.size()]; - int i = 0; - - while(!queue.isEmpty()){ - a[i++] = queue.removeLast().height; - - } - - return a; - } - - public int trap(int[] A) { - - if (A.length <= 2) return 0; - - Deque queue = new LinkedList(); - - int s = 0; - while(s < A.length && A[s] == 0) s++; - - if(s < A.length) - queue.add(new Bar(s, A[s])); - - int water = 0; - - for(int i = s + 1; i < A.length; i++){ - - queue.add(new Bar(i, A[i])); - - water += containWater(queue); - } - - water += trap(reverseAndToInt(queue)); - - return water; - } -} +public class Solution { + + static class Bar{ + int pos; + int height; + + Bar(int pos, int height){ + this.pos = pos; + this.height = height; + } + } + + int containWater(Deque queue){ + + Bar left = queue.peekFirst(); + Bar right = queue.peekLast(); + + int water = 0; + + if(right.height >= left.height){ + + water += Math.min(right.height, left.height) * (right.pos - left.pos - 1); + + queue.removeFirst(); // remove left + + // remove stones + while(queue.size() > 1){ + water -= queue.removeFirst().height; + } + } + + return water; + } + + int[] reverseAndToInt(Deque queue){ + int[] a = new int[queue.size()]; + int i = 0; + + while(!queue.isEmpty()){ + a[i++] = queue.removeLast().height; + + } + + return a; + } + + public int trap(int[] A) { + + if (A.length <= 2) return 0; + + Deque queue = new LinkedList(); + + int s = 0; + while(s < A.length && A[s] == 0) s++; + + if(s < A.length) + queue.add(new Bar(s, A[s])); + + int water = 0; + + for(int i = s + 1; i < A.length; i++){ + + queue.add(new Bar(i, A[i])); + + water += containWater(queue); + } + + water += trap(reverseAndToInt(queue)); + + return water; + } +} diff --git a/triangle/Solution.java b/triangle/Solution.java index 908927b..f9d3d4d 100644 --- a/triangle/Solution.java +++ b/triangle/Solution.java @@ -1,27 +1,27 @@ -public class Solution { - public int minimumTotal(List> triangle) { - - final int size = triangle.size(); - if(size == 0) return 0; - if(size == 1) return triangle.get(0).get(0); - - int[] s = new int[size]; - - int i = 0; - for(int v : triangle.get(size - 1)) s[i++] = v; - - for(i = size - 2; i >=0 ; i--){ - List step = triangle.get(i); - - // s[0] = min(s[0] + step[0], s[1] + step[0]) - - for(int j = 0; j < step.size(); j++){ - s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); - } - - s[step.size()] = Integer.MAX_VALUE; - } - - return s[0]; - } -} +public class Solution { + public int minimumTotal(List> triangle) { + + final int size = triangle.size(); + if(size == 0) return 0; + if(size == 1) return triangle.get(0).get(0); + + int[] s = new int[size]; + + int i = 0; + for(int v : triangle.get(size - 1)) s[i++] = v; + + for(i = size - 2; i >=0 ; i--){ + List step = triangle.get(i); + + // s[0] = min(s[0] + step[0], s[1] + step[0]) + + for(int j = 0; j < step.size(); j++){ + s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); + } + + s[step.size()] = Integer.MAX_VALUE; + } + + return s[0]; + } +} diff --git a/two-sum/Solution.java b/two-sum/Solution.java index 0f00604..00e561b 100644 --- a/two-sum/Solution.java +++ b/two-sum/Solution.java @@ -1,21 +1,21 @@ -public class Solution { - public int[] twoSum(int[] numbers, int target) { - - HashMap m = new HashMap(); - - for(int i = 0; i < numbers.length; i++){ - m.put(target - numbers[i], i); - } - - for(int i = 0; i < numbers.length; i++){ - - Integer v = m.get(numbers[i]); - - if(v != null && v != i){ - return new int[]{i + 1, v + 1}; - } - } - - throw new RuntimeException(); - } -} +public class Solution { + public int[] twoSum(int[] numbers, int target) { + + HashMap m = new HashMap(); + + for(int i = 0; i < numbers.length; i++){ + m.put(target - numbers[i], i); + } + + for(int i = 0; i < numbers.length; i++){ + + Integer v = m.get(numbers[i]); + + if(v != null && v != i){ + return new int[]{i + 1, v + 1}; + } + } + + throw new RuntimeException(); + } +} diff --git a/unique-binary-search-trees-ii/Solution.java b/unique-binary-search-trees-ii/Solution.java index 2448c43..a1aa6c2 100644 --- a/unique-binary-search-trees-ii/Solution.java +++ b/unique-binary-search-trees-ii/Solution.java @@ -1,42 +1,42 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; left = null; right = null; } - * } - */ -public class Solution { - - ArrayList generateTrees(int[] array){ - if (array.length == 0) return new ArrayList(Collections.singletonList(null)); - - ArrayList found = new ArrayList(); - - for(int i = 0; i < array.length; i++){ - - for(TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))){ - for(TreeNode right : generateTrees(Arrays.copyOfRange(array, i + 1, array.length))){ - TreeNode root = new TreeNode(array[i]); - - root.left = left; - root.right = right; - - found.add(root); - } - } - } - - return found; - } - - public List generateTrees(int n) { - - int[] array = new int[n]; - - for(int i = 0; i < n ; i++) array[i] = i + 1; - - return generateTrees(array); - } -} +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; left = null; right = null; } + * } + */ +public class Solution { + + ArrayList generateTrees(int[] array){ + if (array.length == 0) return new ArrayList(Collections.singletonList(null)); + + ArrayList found = new ArrayList(); + + for(int i = 0; i < array.length; i++){ + + for(TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))){ + for(TreeNode right : generateTrees(Arrays.copyOfRange(array, i + 1, array.length))){ + TreeNode root = new TreeNode(array[i]); + + root.left = left; + root.right = right; + + found.add(root); + } + } + } + + return found; + } + + public List generateTrees(int n) { + + int[] array = new int[n]; + + for(int i = 0; i < n ; i++) array[i] = i + 1; + + return generateTrees(array); + } +} diff --git a/unique-binary-search-trees/Solution.java b/unique-binary-search-trees/Solution.java index b3b11b4..bd693cc 100644 --- a/unique-binary-search-trees/Solution.java +++ b/unique-binary-search-trees/Solution.java @@ -1,15 +1,15 @@ -public class Solution { - public int numTrees(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(n == 0) return 1; - - int s = 0; - - for(int i = 0; i < n; i++){ - s += numTrees(i) * numTrees(n - 1 - i); - } - - return s; - } +public class Solution { + public int numTrees(int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(n == 0) return 1; + + int s = 0; + + for(int i = 0; i < n; i++){ + s += numTrees(i) * numTrees(n - 1 - i); + } + + return s; + } } \ No newline at end of file diff --git a/unique-paths-ii/Solution.java b/unique-paths-ii/Solution.java index 221ee49..f8d2b02 100644 --- a/unique-paths-ii/Solution.java +++ b/unique-paths-ii/Solution.java @@ -1,40 +1,40 @@ -public class Solution { - public int uniquePathsWithObstacles(int[][] obstacleGrid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int mx = obstacleGrid.length; - int my = obstacleGrid[0].length; - - if(obstacleGrid[0][0] == 1) return 0; - if(obstacleGrid[mx - 1][my - 1] == 1) return 0; - - int x, y; - - boolean blocked = false; - for(x = 1; x < mx ; x++){ - if (obstacleGrid[x][0] == 1) blocked = true; - obstacleGrid[x][0] = blocked ? 0 : 1; - } - - blocked = false; - for(y = 1; y < my ; y++){ - if (obstacleGrid[0][y] == 1) blocked = true; - obstacleGrid[0][y] = blocked ? 0 : 1; - } - - - obstacleGrid[0][0] = 1; - - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my; y++){ - if(obstacleGrid[x][y] == 1) - obstacleGrid[x][y] = 0; - else - obstacleGrid[x][y] = obstacleGrid[x - 1][y] + obstacleGrid[x][y - 1]; - } - } - - return obstacleGrid[mx - 1][my - 1]; - - } +public class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + // Note: The Solution object is instantiated only once and is reused by each test case. + int mx = obstacleGrid.length; + int my = obstacleGrid[0].length; + + if(obstacleGrid[0][0] == 1) return 0; + if(obstacleGrid[mx - 1][my - 1] == 1) return 0; + + int x, y; + + boolean blocked = false; + for(x = 1; x < mx ; x++){ + if (obstacleGrid[x][0] == 1) blocked = true; + obstacleGrid[x][0] = blocked ? 0 : 1; + } + + blocked = false; + for(y = 1; y < my ; y++){ + if (obstacleGrid[0][y] == 1) blocked = true; + obstacleGrid[0][y] = blocked ? 0 : 1; + } + + + obstacleGrid[0][0] = 1; + + + for(x = 1; x < mx ; x++){ + for(y = 1; y < my; y++){ + if(obstacleGrid[x][y] == 1) + obstacleGrid[x][y] = 0; + else + obstacleGrid[x][y] = obstacleGrid[x - 1][y] + obstacleGrid[x][y - 1]; + } + } + + return obstacleGrid[mx - 1][my - 1]; + + } } \ No newline at end of file diff --git a/unique-paths/Solution.java b/unique-paths/Solution.java index 7f70ad8..d8a3e36 100644 --- a/unique-paths/Solution.java +++ b/unique-paths/Solution.java @@ -1,26 +1,26 @@ -public class Solution { - public int uniquePaths(int m, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(m == 0 || n == 0) return 0; - - int[][] matrix = new int[m][n]; - - int x, y; - - for(x = 0; x < m; x++) - matrix[x][0] = 1; - - for(y = 0; y < n; y++) - matrix[0][y] = 1; - - - for(x = 1; x < m; x++){ - for(y = 1; y < n; y++){ - matrix[x][y] = matrix[x - 1][y] + matrix[x][y - 1]; - } - } - - return matrix[m - 1][n - 1]; - } +public class Solution { + public int uniquePaths(int m, int n) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + if(m == 0 || n == 0) return 0; + + int[][] matrix = new int[m][n]; + + int x, y; + + for(x = 0; x < m; x++) + matrix[x][0] = 1; + + for(y = 0; y < n; y++) + matrix[0][y] = 1; + + + for(x = 1; x < m; x++){ + for(y = 1; y < n; y++){ + matrix[x][y] = matrix[x - 1][y] + matrix[x][y - 1]; + } + } + + return matrix[m - 1][n - 1]; + } } \ No newline at end of file diff --git a/valid-number/Solution.java b/valid-number/Solution.java index 761f4c7..96337f3 100644 --- a/valid-number/Solution.java +++ b/valid-number/Solution.java @@ -1,44 +1,44 @@ -public class Solution { - - - public boolean isNumber(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if ( s == null) return false; - else if( s.length() == 0 ) return false; - - char[] chars = s.toCharArray(); - int st = 0 , ed = chars.length - 1; - - while((st < ed ) && chars[st] == ' ') st++; - while((st < ed ) && chars[ed] == ' ') ed--; - - if(chars[st] == ' ') return false; - - boolean dot = false; - boolean ex = false; - boolean num = false; - - for(int i = st; i <= ed; i++ ){ - char c = chars[i]; - if ('0' <= c && c <= '9'){ - num = true; - }else if ( c == 'e'){ - if(ex) return false; - if(!num) return false; - ex = true; - num = false; - dot = false; - }else if ( c == '.'){ - if(dot) return false; - if(ex) return false; - dot = true; - }else if ( c == '-' || c == '+' ){ - if(num || dot)return false; - }else - return false; - } - - return num; - - } +public class Solution { + + + public boolean isNumber(String s) { + // Note: The Solution object is instantiated only once and is reused by each test case. + if ( s == null) return false; + else if( s.length() == 0 ) return false; + + char[] chars = s.toCharArray(); + int st = 0 , ed = chars.length - 1; + + while((st < ed ) && chars[st] == ' ') st++; + while((st < ed ) && chars[ed] == ' ') ed--; + + if(chars[st] == ' ') return false; + + boolean dot = false; + boolean ex = false; + boolean num = false; + + for(int i = st; i <= ed; i++ ){ + char c = chars[i]; + if ('0' <= c && c <= '9'){ + num = true; + }else if ( c == 'e'){ + if(ex) return false; + if(!num) return false; + ex = true; + num = false; + dot = false; + }else if ( c == '.'){ + if(dot) return false; + if(ex) return false; + dot = true; + }else if ( c == '-' || c == '+' ){ + if(num || dot)return false; + }else + return false; + } + + return num; + + } } \ No newline at end of file diff --git a/valid-palindrome/Solution.java b/valid-palindrome/Solution.java index d69b5e9..416312c 100644 --- a/valid-palindrome/Solution.java +++ b/valid-palindrome/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - - boolean valid(char[] chars, int i){ - return !(('A' <= chars[i] && chars[i]<= 'Z') - || ('a' <= chars[i] && chars[i]<= 'z') - || ('0' <= chars[i] && chars[i]<= '9')); - } - - public boolean isPalindrome(String s) { - if(s == null) return false; - - char[] chars = s.toLowerCase().toCharArray(); - int i = 0, j = chars.length - 1; - - while(i < j){ - - // ignore space etc. - while( (i < j) && valid(chars, i)) i++; - while( (i < j) && valid(chars, j)) j--; - - if(chars[i] != chars[j]) return false; - - i++; - j--; - } - - return true; - } -} +public class Solution { + + boolean valid(char[] chars, int i){ + return !(('A' <= chars[i] && chars[i]<= 'Z') + || ('a' <= chars[i] && chars[i]<= 'z') + || ('0' <= chars[i] && chars[i]<= '9')); + } + + public boolean isPalindrome(String s) { + if(s == null) return false; + + char[] chars = s.toLowerCase().toCharArray(); + int i = 0, j = chars.length - 1; + + while(i < j){ + + // ignore space etc. + while( (i < j) && valid(chars, i)) i++; + while( (i < j) && valid(chars, j)) j--; + + if(chars[i] != chars[j]) return false; + + i++; + j--; + } + + return true; + } +} diff --git a/valid-parentheses/Solution.java b/valid-parentheses/Solution.java index 2e3226e..92af536 100644 --- a/valid-parentheses/Solution.java +++ b/valid-parentheses/Solution.java @@ -1,29 +1,29 @@ -public class Solution { - - boolean couple(Character l, Character r){ - if(l == null) return false; - return (l == '[' && r == ']') || (l == '(' && r == ')') || (l == '{' && r == '}'); - } - - public boolean isValid(String s) { - if(s == null) return false; - - char[] chars = s.toCharArray(); - - if(chars.length == 0 || chars.length % 2 == 1) return false; - - LinkedList stack = new LinkedList(); - - for(char c: chars){ - Character peek = stack.peek(); - - if(couple(peek, c)){ - stack.pop(); - }else{ - stack.push(c); - } - } - - return stack.size() == 0; - } -} +public class Solution { + + boolean couple(Character l, Character r){ + if(l == null) return false; + return (l == '[' && r == ']') || (l == '(' && r == ')') || (l == '{' && r == '}'); + } + + public boolean isValid(String s) { + if(s == null) return false; + + char[] chars = s.toCharArray(); + + if(chars.length == 0 || chars.length % 2 == 1) return false; + + LinkedList stack = new LinkedList(); + + for(char c: chars){ + Character peek = stack.peek(); + + if(couple(peek, c)){ + stack.pop(); + }else{ + stack.push(c); + } + } + + return stack.size() == 0; + } +} diff --git a/valid-sudoku/Solution.java b/valid-sudoku/Solution.java index 9fb79a2..0d0a77f 100644 --- a/valid-sudoku/Solution.java +++ b/valid-sudoku/Solution.java @@ -1,55 +1,55 @@ -public class Solution { - public boolean isValidSudoku(char[][] board) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } +public class Solution { + public boolean isValidSudoku(char[][] board) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + int mx = board.length; + int my = board[0].length; + + int x, y; + + for(x = 0; x < mx; x++){ + HashSet col = new HashSet(); + for(y = 0; y < my; y++){ + char c = board[x][y]; + if(c != '.'){ + if(col.contains(c)) return false; + + col.add(c); + } + } + } + + for(y = 0; y < my; y++){ + HashSet row = new HashSet(); + for(x = 0; x < mx; x++){ + char c = board[x][y]; + if(c != '.'){ + if(row.contains(c)) return false; + + row.add(c); + } + } + } + + for(x = 0; x < mx; x += 3){ + for(y = 0; y < my; y += 3){ + + HashSet block = new HashSet(); + + for(int offset = 0; offset < 9; offset++){ + int ox = offset % 3; + int oy = offset / 3; + + char c = board[x + ox][y + oy]; + if(c != '.'){ + if(block.contains(c)) return false; + + block.add(c); + } + } + } + } + + return true; + } } \ No newline at end of file diff --git a/validate-binary-search-tree/Solution.java b/validate-binary-search-tree/Solution.java index cf9d1a6..03ab776 100644 --- a/validate-binary-search-tree/Solution.java +++ b/validate-binary-search-tree/Solution.java @@ -1,38 +1,38 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int last; - boolean failed; - - void inorder(TreeNode root){ - - if(root == null) return; - if(failed) return; - - inorder(root.left); - - if( last >= root.val) failed = true; - last = root.val; - - inorder(root.right); - - } - - public boolean isValidBST(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - last = Integer.MIN_VALUE; - failed = false; - - if(root == null) return true; - inorder(root); - return !failed; - } +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int last; + boolean failed; + + void inorder(TreeNode root){ + + if(root == null) return; + if(failed) return; + + inorder(root.left); + + if( last >= root.val) failed = true; + last = root.val; + + inorder(root.right); + + } + + public boolean isValidBST(TreeNode root) { + // Note: The Solution object is instantiated only once and is reused by each test case. + last = Integer.MIN_VALUE; + failed = false; + + if(root == null) return true; + inorder(root); + return !failed; + } } \ No newline at end of file diff --git a/wildcard-matching/Solution.java b/wildcard-matching/Solution.java index b889678..62c4dd1 100644 --- a/wildcard-matching/Solution.java +++ b/wildcard-matching/Solution.java @@ -1,58 +1,58 @@ -public class Solution { - public boolean isMatch(String s, String p) { - - - char[] S = s.toCharArray(); - char[] P = p.toCharArray(); - - int checkpointS = -1; - int checkpointP = -1; - - int j = 0; - - for(int i = 0; i < S.length; /*void*/){ - - if(j < P.length) { - - if(S[i] == P[j] || P[j] == '?'){ - i++; - j++; - continue; - } - - if(P[j] == '*'){ - - checkpointS = i; - checkpointP = j; - - j++; - continue; - } - } - - // mismatch - - if(checkpointS >= 0){ - - checkpointS++; - - // restore - i = checkpointS; - j = checkpointP + 1; - continue; - } - - return false; - } - - while(j < P.length) { - if(P[j] == '*'){ - j++; - } else { - return false; - } - } - - return true; - } +public class Solution { + public boolean isMatch(String s, String p) { + + + char[] S = s.toCharArray(); + char[] P = p.toCharArray(); + + int checkpointS = -1; + int checkpointP = -1; + + int j = 0; + + for(int i = 0; i < S.length; /*void*/){ + + if(j < P.length) { + + if(S[i] == P[j] || P[j] == '?'){ + i++; + j++; + continue; + } + + if(P[j] == '*'){ + + checkpointS = i; + checkpointP = j; + + j++; + continue; + } + } + + // mismatch + + if(checkpointS >= 0){ + + checkpointS++; + + // restore + i = checkpointS; + j = checkpointP + 1; + continue; + } + + return false; + } + + while(j < P.length) { + if(P[j] == '*'){ + j++; + } else { + return false; + } + } + + return true; + } } \ No newline at end of file diff --git a/word-break-ii/Solution.java b/word-break-ii/Solution.java index 1a26393..11df5fe 100644 --- a/word-break-ii/Solution.java +++ b/word-break-ii/Solution.java @@ -1,67 +1,67 @@ -public class Solution { - - String join(List list){ - if(list.isEmpty()) return ""; - - StringBuilder s = new StringBuilder(list.get(0)); - - for(int i = 1; i < list.size(); i++){ - s.append(' '); - s.append(list.get(i)); - } - - return s.toString(); - } - - ArrayList[] P; - char[] S; - ArrayList rt; - - void joinAll(int offset, LinkedList parents){ - - if(P[offset].isEmpty()){ - - rt.add(join(parents)); - return; - } - - for(Integer p : P[offset]){ - - parents.push(new String(S, p, offset - p)); - - joinAll(p, parents); - - parents.pop(); - } - - } - - public List wordBreak(String s, Set dict) { - S = s.toCharArray(); - - P = new ArrayList[S.length + 1]; - P[0] = new ArrayList(); - - for(int i = 0; i < S.length; i++){ - for(int j = 0; j <= i; j++){ - String w = new String(S, j, i - j + 1); - if(P[j] != null && dict.contains(w)){ - - if(P[i + 1] == null){ - P[i + 1] = new ArrayList(); - } - - P[i + 1].add(j); - } - } - } - - rt = new ArrayList(); - - if(P[S.length] != null){ - joinAll(S.length, new LinkedList()); - } - - return rt; - } -} +public class Solution { + + String join(List list){ + if(list.isEmpty()) return ""; + + StringBuilder s = new StringBuilder(list.get(0)); + + for(int i = 1; i < list.size(); i++){ + s.append(' '); + s.append(list.get(i)); + } + + return s.toString(); + } + + ArrayList[] P; + char[] S; + ArrayList rt; + + void joinAll(int offset, LinkedList parents){ + + if(P[offset].isEmpty()){ + + rt.add(join(parents)); + return; + } + + for(Integer p : P[offset]){ + + parents.push(new String(S, p, offset - p)); + + joinAll(p, parents); + + parents.pop(); + } + + } + + public List wordBreak(String s, Set dict) { + S = s.toCharArray(); + + P = new ArrayList[S.length + 1]; + P[0] = new ArrayList(); + + for(int i = 0; i < S.length; i++){ + for(int j = 0; j <= i; j++){ + String w = new String(S, j, i - j + 1); + if(P[j] != null && dict.contains(w)){ + + if(P[i + 1] == null){ + P[i + 1] = new ArrayList(); + } + + P[i + 1].add(j); + } + } + } + + rt = new ArrayList(); + + if(P[S.length] != null){ + joinAll(S.length, new LinkedList()); + } + + return rt; + } +} diff --git a/word-break/Solution.java b/word-break/Solution.java index d749cf7..ddb0b2c 100644 --- a/word-break/Solution.java +++ b/word-break/Solution.java @@ -1,23 +1,23 @@ -public class Solution { - public boolean wordBreak(String s, Set dict) { - - char[] S = s.toCharArray(); - - boolean[] P = new boolean[S.length + 1]; - P[0] = true; - - for(int i = 0; i < S.length; i++){ - - for(int j = 0; j <= i; j++){ - if(P[j] && dict.contains(new String(S, j, i - j + 1))){ - P[i + 1] = true; - continue; - } - } - } - - return P[S.length]; - - - } +public class Solution { + public boolean wordBreak(String s, Set dict) { + + char[] S = s.toCharArray(); + + boolean[] P = new boolean[S.length + 1]; + P[0] = true; + + for(int i = 0; i < S.length; i++){ + + for(int j = 0; j <= i; j++){ + if(P[j] && dict.contains(new String(S, j, i - j + 1))){ + P[i + 1] = true; + continue; + } + } + } + + return P[S.length]; + + + } } \ No newline at end of file diff --git a/word-ladder-ii/Solution.java b/word-ladder-ii/Solution.java index ae2744c..9243888 100644 --- a/word-ladder-ii/Solution.java +++ b/word-ladder-ii/Solution.java @@ -1,136 +1,136 @@ -public class Solution { - - static class Word { - - String word; - Set next; - - boolean end; - - Word(String word){ - this.word = word; - } - } - - static class Trace { - - Word obj; - Trace prev; - - Trace(Word obj,Trace prev){ - this.obj = obj; - this.prev = prev; - } - } - - - HashMap wmap; - - void connect(Word w, Set dict){ - if(w.next != null) return; - - Set n = new HashSet(); - - char[] ws = w.word.toCharArray(); - - for(int i = 0; i < ws.length; i++){ - char t = ws[i]; - - for(char r = 'a'; r <= 'z'; r++){ - ws[i] = r; - - String d = new String(ws); - if(dict.contains(d)){ - Word c = wmap.get(d); - n.add(c); - } - } - - ws[i] = t; - } - - w.next = n; - } - - - public List> findLadders(String start, String end, Set dict) { - - - List> rt = new ArrayList>(); - - wmap = new HashMap(); - - for(String d : dict){ - Word w = new Word(d); - wmap.put(d, w); - } - - Word _end = new Word(end); - _end.end = true; - wmap.put(end, _end); - - // help to connected to end - dict.add(end); - - - final Trace SEP = new Trace(null, null); - LinkedList queue = new LinkedList(); - - queue.add(new Trace(new Word(start), null)); - queue.add(SEP); - - boolean found = false; - - HashSet vi = new HashSet(); - HashSet svi = new HashSet(); - - while(!queue.isEmpty()){ - - Trace step = queue.poll(); - - if(step == SEP) { - vi.addAll(svi); - svi.clear(); - - if (found) break; - if (!queue.isEmpty()) queue.add(SEP); - - } else { - - Word word = step.obj; - connect(word, dict); - - - if(word.end){ - - LinkedList r = new LinkedList(); - - - Trace t = step; - - while (t != null){ - r.addFirst(t.obj.word); - t = t.prev; - } - - rt.add(r); - - found = true; - - }else if(!found){ // prevent deeper level to be visited - - for (Word p : word.next) { - - if(!vi.contains(p)) { - queue.add(new Trace(p, step)); - svi.add(p); - } - } - } - } - } - - - return rt; - } -} +public class Solution { + + static class Word { + + String word; + Set next; + + boolean end; + + Word(String word){ + this.word = word; + } + } + + static class Trace { + + Word obj; + Trace prev; + + Trace(Word obj,Trace prev){ + this.obj = obj; + this.prev = prev; + } + } + + + HashMap wmap; + + void connect(Word w, Set dict){ + if(w.next != null) return; + + Set n = new HashSet(); + + char[] ws = w.word.toCharArray(); + + for(int i = 0; i < ws.length; i++){ + char t = ws[i]; + + for(char r = 'a'; r <= 'z'; r++){ + ws[i] = r; + + String d = new String(ws); + if(dict.contains(d)){ + Word c = wmap.get(d); + n.add(c); + } + } + + ws[i] = t; + } + + w.next = n; + } + + + public List> findLadders(String start, String end, Set dict) { + + + List> rt = new ArrayList>(); + + wmap = new HashMap(); + + for(String d : dict){ + Word w = new Word(d); + wmap.put(d, w); + } + + Word _end = new Word(end); + _end.end = true; + wmap.put(end, _end); + + // help to connected to end + dict.add(end); + + + final Trace SEP = new Trace(null, null); + LinkedList queue = new LinkedList(); + + queue.add(new Trace(new Word(start), null)); + queue.add(SEP); + + boolean found = false; + + HashSet vi = new HashSet(); + HashSet svi = new HashSet(); + + while(!queue.isEmpty()){ + + Trace step = queue.poll(); + + if(step == SEP) { + vi.addAll(svi); + svi.clear(); + + if (found) break; + if (!queue.isEmpty()) queue.add(SEP); + + } else { + + Word word = step.obj; + connect(word, dict); + + + if(word.end){ + + LinkedList r = new LinkedList(); + + + Trace t = step; + + while (t != null){ + r.addFirst(t.obj.word); + t = t.prev; + } + + rt.add(r); + + found = true; + + }else if(!found){ // prevent deeper level to be visited + + for (Word p : word.next) { + + if(!vi.contains(p)) { + queue.add(new Trace(p, step)); + svi.add(p); + } + } + } + } + } + + + return rt; + } +} diff --git a/word-ladder/Solution.java b/word-ladder/Solution.java index 070fbfb..ce069f3 100644 --- a/word-ladder/Solution.java +++ b/word-ladder/Solution.java @@ -1,59 +1,59 @@ -public class Solution { - - public int ladderLength(String start, String end, Set dict) { - - LinkedList queue = new LinkedList(); - final String END = new String(); - - queue.add(start); - queue.add(END); - - int level = 0; - HashSet vi = new HashSet(); - - while(!queue.isEmpty()){ - - String current = queue.poll(); - - if(current == END){ - level++; - - if(!queue.isEmpty()) queue.add(END); - }else{ - - if(end.equals(current)) - return level + 1; - - char[] word = current.toCharArray(); - - for(int i = 0; i < word.length; i++){ - - char old = word[i]; - - for(char j = 'a'; j <= 'z' ; j++){ - - if(j == old) - continue; - - word[i] = j; - - String s = new String(word); - - if(dict.contains(s) && !vi.contains(s)){ - queue.add(s); - vi.add(s); - } - - } - - word[i] = old; - } - - } - - } - - return 0; - - } -} +public class Solution { + + public int ladderLength(String start, String end, Set dict) { + + LinkedList queue = new LinkedList(); + final String END = new String(); + + queue.add(start); + queue.add(END); + + int level = 0; + HashSet vi = new HashSet(); + + while(!queue.isEmpty()){ + + String current = queue.poll(); + + if(current == END){ + level++; + + if(!queue.isEmpty()) queue.add(END); + }else{ + + if(end.equals(current)) + return level + 1; + + char[] word = current.toCharArray(); + + for(int i = 0; i < word.length; i++){ + + char old = word[i]; + + for(char j = 'a'; j <= 'z' ; j++){ + + if(j == old) + continue; + + word[i] = j; + + String s = new String(word); + + if(dict.contains(s) && !vi.contains(s)){ + queue.add(s); + vi.add(s); + } + + } + + word[i] = old; + } + + } + + } + + return 0; + + } +} diff --git a/word-search/Solution.java b/word-search/Solution.java index 8a5a55c..ec307f3 100644 --- a/word-search/Solution.java +++ b/word-search/Solution.java @@ -1,85 +1,85 @@ -public class Solution { - - class XY{ - int x; - int y; - - XY(int x, int y) { - this.x = x; - this.y = y; - } - } - - XY[] stack; - - int mx; - int my; - - boolean search(char[][] board, char[] cs, final int index){ - - if(index >= cs.length) return true; - - // final int mx = board.length, my = board[0].length; - - final int x = stack[index - 1].x, y = stack[index - 1].y; - - next: - for(XY xy : new XY[]{new XY(x - 1, y), new XY(x + 1, y), new XY(x, y - 1), new XY(x, y + 1) }){ - int _x = xy.x; - int _y = xy.y; - - for(int i = 0; i < index ; i++){ - if(stack[i].x == _x && stack[i].y == _y) - continue next; - } - - if(_x >=0 && _x < mx && _y >= 0 && _y < my){ - if(board[_x][_y] == cs[index]){ - stack[index] = new XY(_x , _y); - - if(search(board, cs, index + 1)) - return true; - } - } - - } - - return false; - } - - - public boolean exist(char[][] board, String word) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (board.length == 0) return false; - - - int x = 0, y = 0; - - mx = board.length; - my = board[0].length; - - char[] str = word.toCharArray(); - - - //if( str.length > mx * my ) return false; // fuck.. - - stack = new XY[str.length]; - - if(str.length == 0) return false; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if( board[x][y] == str[0] ){ - - stack[0] = new XY(x, y); - if(search(board, str, 1)) - return true; - } - } - } - - return false; - } +public class Solution { + + class XY{ + int x; + int y; + + XY(int x, int y) { + this.x = x; + this.y = y; + } + } + + XY[] stack; + + int mx; + int my; + + boolean search(char[][] board, char[] cs, final int index){ + + if(index >= cs.length) return true; + + // final int mx = board.length, my = board[0].length; + + final int x = stack[index - 1].x, y = stack[index - 1].y; + + next: + for(XY xy : new XY[]{new XY(x - 1, y), new XY(x + 1, y), new XY(x, y - 1), new XY(x, y + 1) }){ + int _x = xy.x; + int _y = xy.y; + + for(int i = 0; i < index ; i++){ + if(stack[i].x == _x && stack[i].y == _y) + continue next; + } + + if(_x >=0 && _x < mx && _y >= 0 && _y < my){ + if(board[_x][_y] == cs[index]){ + stack[index] = new XY(_x , _y); + + if(search(board, cs, index + 1)) + return true; + } + } + + } + + return false; + } + + + public boolean exist(char[][] board, String word) { + // IMPORTANT: Please reset any member data you declared, as + // the same Solution instance will be reused for each test case. + + if (board.length == 0) return false; + + + int x = 0, y = 0; + + mx = board.length; + my = board[0].length; + + char[] str = word.toCharArray(); + + + //if( str.length > mx * my ) return false; // fuck.. + + stack = new XY[str.length]; + + if(str.length == 0) return false; + + for(x = 0; x < mx; x++){ + for(y = 0; y < my; y++){ + if( board[x][y] == str[0] ){ + + stack[0] = new XY(x, y); + if(search(board, str, 1)) + return true; + } + } + } + + return false; + } } \ No newline at end of file diff --git a/zigzag-conversion/Solution.java b/zigzag-conversion/Solution.java index 26f7078..63ef178 100644 --- a/zigzag-conversion/Solution.java +++ b/zigzag-conversion/Solution.java @@ -1,56 +1,56 @@ -public class Solution { - public String convert(String s, int nRows) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - //row = 4 - /* - * * * - * * * * - * * * * - * * - |r-2+1| - - col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) - */ - - if(nRows == 1) return s; - - int nCols = (nRows - 2 + 1) * (s.length() / (nRows + nRows - 2) + 1); - char[][] paper = new char[nCols][nRows]; - - //int ps = 0; - char[] str = s.toCharArray(); - - int pr = 0, pc = 0; - - boolean direction = false; // true for down false for up , start up = come from up - - - for(char c : str){ - paper[pc][pr] = c; - - if(pr == 0 || pr == nRows - 1){ - direction = !direction; - } - - if(direction){ - pr++; - }else{ - pr--; - pc++; - } - } - - String rt = ""; - for(int i = 0; i < nRows; i++){ - for(int j = 0; j < nCols; j++){ - if(paper[j][i] != 0){ - rt += paper[j][i]; - } - } - } - - return rt; - - } +public class Solution { + public String convert(String s, int nRows) { + // Note: The Solution object is instantiated only once and is reused by each test case. + + //row = 4 + /* + * * * + * * * * + * * * * + * * + |r-2+1| + + col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) + */ + + if(nRows == 1) return s; + + int nCols = (nRows - 2 + 1) * (s.length() / (nRows + nRows - 2) + 1); + char[][] paper = new char[nCols][nRows]; + + //int ps = 0; + char[] str = s.toCharArray(); + + int pr = 0, pc = 0; + + boolean direction = false; // true for down false for up , start up = come from up + + + for(char c : str){ + paper[pc][pr] = c; + + if(pr == 0 || pr == nRows - 1){ + direction = !direction; + } + + if(direction){ + pr++; + }else{ + pr--; + pc++; + } + } + + String rt = ""; + for(int i = 0; i < nRows; i++){ + for(int j = 0; j < nCols; j++){ + if(paper[j][i] != 0){ + rt += paper[j][i]; + } + } + } + + return rt; + + } } \ No newline at end of file From ea1eb4c2206ba097a7e184f98fd6f13a6cd1e21f Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 30 Dec 2014 18:01:41 +0800 Subject: [PATCH 031/195] add fact trailing zero --- factorial-trailing-zeroes/README.md | 0 factorial-trailing-zeroes/Solution.java | 33 +++++++++++++++++++++++++ factorial-trailing-zeroes/index.md | 9 +++++++ 3 files changed, 42 insertions(+) create mode 100644 factorial-trailing-zeroes/README.md create mode 100644 factorial-trailing-zeroes/Solution.java create mode 100644 factorial-trailing-zeroes/index.md diff --git a/factorial-trailing-zeroes/README.md b/factorial-trailing-zeroes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/factorial-trailing-zeroes/Solution.java b/factorial-trailing-zeroes/Solution.java new file mode 100644 index 0000000..e3c95d5 --- /dev/null +++ b/factorial-trailing-zeroes/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + public int trailingZeroes(int n) { + + int count = 0; + + int c2 = 0; // count of 2 + int c5 = 0; // count of 5 + + for (int i = 1; i <= n; i++){ + int m = i; + + while(m % 5 == 0){ + m /= 5; + c5++; + } + + while(m % 2 == 0){ + m /= 2; + c2++; + } + + int c = Math.min(c2, c5); + + count += c; + c2 -= c; + c5 -= c; + + } + + return count; + + } +} diff --git a/factorial-trailing-zeroes/index.md b/factorial-trailing-zeroes/index.md new file mode 100644 index 0000000..ffd0584 --- /dev/null +++ b/factorial-trailing-zeroes/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Factorial Trailing Zeroes +date: 2014-12-30 18:00:00+08:00 +leetcode_id: 172 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From b4332ad6283b31dc3cdd1d573d2e36afc0f7ec31 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 30 Dec 2014 18:05:38 +0800 Subject: [PATCH 032/195] add fact trailing zero to gh-page --- .../_root/factorial-trailing-zeroes/README.md | 0 .../factorial-trailing-zeroes/Solution.java | 33 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 _includes/_root/factorial-trailing-zeroes/README.md create mode 100644 _includes/_root/factorial-trailing-zeroes/Solution.java diff --git a/_includes/_root/factorial-trailing-zeroes/README.md b/_includes/_root/factorial-trailing-zeroes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/factorial-trailing-zeroes/Solution.java b/_includes/_root/factorial-trailing-zeroes/Solution.java new file mode 100644 index 0000000..e3c95d5 --- /dev/null +++ b/_includes/_root/factorial-trailing-zeroes/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + public int trailingZeroes(int n) { + + int count = 0; + + int c2 = 0; // count of 2 + int c5 = 0; // count of 5 + + for (int i = 1; i <= n; i++){ + int m = i; + + while(m % 5 == 0){ + m /= 5; + c5++; + } + + while(m % 2 == 0){ + m /= 2; + c2++; + } + + int c = Math.min(c2, c5); + + count += c; + c2 -= c; + c5 -= c; + + } + + return count; + + } +} From 8d8b3e4ceb908c8c2ddba4f6dc49fc8417747370 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 31 Dec 2014 16:16:36 +0800 Subject: [PATCH 033/195] add 173 bst iter --- binary-search-tree-iterator/BSTIterator.java | 1 + binary-search-tree-iterator/README.md | 0 binary-search-tree-iterator/Solution.java | 91 ++++++++++++++++++++ binary-search-tree-iterator/index.md | 9 ++ 4 files changed, 101 insertions(+) create mode 120000 binary-search-tree-iterator/BSTIterator.java create mode 100644 binary-search-tree-iterator/README.md create mode 100644 binary-search-tree-iterator/Solution.java create mode 100644 binary-search-tree-iterator/index.md diff --git a/binary-search-tree-iterator/BSTIterator.java b/binary-search-tree-iterator/BSTIterator.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/binary-search-tree-iterator/BSTIterator.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/binary-search-tree-iterator/README.md b/binary-search-tree-iterator/README.md new file mode 100644 index 0000000..e69de29 diff --git a/binary-search-tree-iterator/Solution.java b/binary-search-tree-iterator/Solution.java new file mode 100644 index 0000000..5776345 --- /dev/null +++ b/binary-search-tree-iterator/Solution.java @@ -0,0 +1,91 @@ +/** +* Definition for binary tree +* public class TreeNode { +* int val; +* TreeNode left; +* TreeNode right; +* TreeNode(int x) { val = x; } +* } +*/ + +public class BSTIterator { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + Deque stack = new LinkedList(); + + public BSTIterator(TreeNode root) { + if(root != null) { + stack.push(new StackState(root)); + } + } + + /** @return whether we have a next smallest number */ + public boolean hasNext() { + if(!stack.isEmpty()){ + StackState current = stack.pop(); + switch(current.returnAddress){ + case PRE: + case IN: + stack.push(current); + return true; + + case POST: + if(current.param.right != null){ + stack.push(new StackState(current.param.right)); + return true; + } + } + return hasNext(); + } + return false; + } + + /** @return the next smallest number */ + public int next() { + + StackState current = stack.pop(); + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + break; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + stack.push(current); + return current.param.val; + + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + break; + } + } + return next(); + } +} + +/** +* Your BSTIterator will be called like this: +* BSTIterator i = new BSTIterator(root); +* while (i.hasNext()) v[f()] = i.next(); +*/ diff --git a/binary-search-tree-iterator/index.md b/binary-search-tree-iterator/index.md new file mode 100644 index 0000000..46925ee --- /dev/null +++ b/binary-search-tree-iterator/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Binary Search Tree Iterator +date: 2014-12-31 16:13:14+08:00 +leetcode_id: 173 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From e0dab17a0bf6a4052450087fb6a2c433dee52f74 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 31 Dec 2014 16:17:28 +0800 Subject: [PATCH 034/195] fix update time --- 3sum-closest/index.md | 2 +- 3sum/index.md | 2 +- 4sum/index.md | 2 +- add-binary/index.md | 2 +- add-two-numbers/index.md | 2 +- anagrams/index.md | 2 +- balanced-binary-tree/index.md | 2 +- best-time-to-buy-and-sell-stock-ii/index.md | 2 +- best-time-to-buy-and-sell-stock-iii/index.md | 2 +- best-time-to-buy-and-sell-stock/index.md | 2 +- binary-search-tree-iterator/index.md | 2 +- binary-tree-inorder-traversal/index.md | 2 +- binary-tree-level-order-traversal-ii/index.md | 2 +- binary-tree-level-order-traversal/index.md | 2 +- binary-tree-maximum-path-sum/index.md | 2 +- binary-tree-postorder-traversal/index.md | 2 +- binary-tree-preorder-traversal/index.md | 2 +- binary-tree-zigzag-level-order-traversal/index.md | 2 +- candy/index.md | 2 +- climbing-stairs/index.md | 2 +- clone-graph/index.md | 2 +- combination-sum-ii/index.md | 2 +- combination-sum/index.md | 2 +- combinations/index.md | 2 +- .../index.md | 2 +- .../index.md | 2 +- container-with-most-water/index.md | 2 +- convert-sorted-array-to-binary-search-tree/index.md | 2 +- convert-sorted-list-to-binary-search-tree/index.md | 2 +- copy-list-with-random-pointer/index.md | 2 +- count-and-say/index.md | 2 +- decode-ways/index.md | 2 +- distinct-subsequences/index.md | 2 +- divide-two-integers/index.md | 2 +- edit-distance/index.md | 2 +- evaluate-reverse-polish-notation/index.md | 2 +- factorial-trailing-zeroes/index.md | 2 +- find-minimum-in-rotated-sorted-array-ii/index.md | 2 +- find-minimum-in-rotated-sorted-array/index.md | 2 +- find-peak-element/index.md | 2 +- first-missing-positive/index.md | 2 +- flatten-binary-tree-to-linked-list/index.md | 2 +- gas-station/index.md | 2 +- generate-parentheses/index.md | 2 +- gray-code/index.md | 2 +- implement-strstr/index.md | 2 +- insert-interval/index.md | 2 +- insertion-sort-list/index.md | 2 +- integer-to-roman/index.md | 2 +- interleaving-string/index.md | 2 +- intersection-of-two-linked-lists/index.md | 2 +- jump-game-ii/index.md | 2 +- jump-game/index.md | 2 +- largest-rectangle-in-histogram/index.md | 2 +- length-of-last-word/index.md | 2 +- letter-combinations-of-a-phone-number/index.md | 2 +- linked-list-cycle-ii/index.md | 2 +- linked-list-cycle/index.md | 2 +- longest-common-prefix/index.md | 2 +- longest-consecutive-sequence/index.md | 2 +- longest-palindromic-substring/index.md | 2 +- longest-substring-with-at-most-two-distinct-characters/index.md | 2 +- longest-substring-without-repeating-characters/index.md | 2 +- longest-valid-parentheses/index.md | 2 +- lru-cache/index.md | 2 +- max-points-on-a-line/index.md | 2 +- maximal-rectangle/index.md | 2 +- maximum-depth-of-binary-tree/index.md | 2 +- maximum-gap/index.md | 2 +- maximum-subarray/index.md | 2 +- median-of-two-sorted-arrays/index.md | 2 +- merge-intervals/index.md | 2 +- merge-k-sorted-lists/index.md | 2 +- merge-sorted-array/index.md | 2 +- merge-two-sorted-lists/index.md | 2 +- minimum-depth-of-binary-tree/index.md | 2 +- minimum-path-sum/index.md | 2 +- minimum-window-substring/index.md | 2 +- missing-ranges/index.md | 2 +- multiply-strings/index.md | 2 +- n-queens-ii/index.md | 2 +- n-queens/index.md | 2 +- next-permutation/index.md | 2 +- one-edit-distance/index.md | 2 +- palindrome-number/index.md | 2 +- palindrome-partitioning-ii/index.md | 2 +- palindrome-partitioning/index.md | 2 +- partition-list/index.md | 2 +- pascals-triangle-ii/index.md | 2 +- pascals-triangle/index.md | 2 +- path-sum-ii/index.md | 2 +- path-sum/index.md | 2 +- permutation-sequence/index.md | 2 +- permutations-ii/index.md | 2 +- permutations/index.md | 2 +- plus-one/index.md | 2 +- populating-next-right-pointers-in-each-node-ii/index.md | 2 +- populating-next-right-pointers-in-each-node/index.md | 2 +- powx-n/index.md | 2 +- read-n-characters-given-read4-ii-call-multiple-times/index.md | 2 +- read-n-characters-given-read4/index.md | 2 +- recover-binary-search-tree/index.md | 2 +- regular-expression-matching/index.md | 2 +- remove-duplicates-from-sorted-array-ii/index.md | 2 +- remove-duplicates-from-sorted-array/index.md | 2 +- remove-duplicates-from-sorted-list-ii/index.md | 2 +- remove-duplicates-from-sorted-list/index.md | 2 +- remove-element/index.md | 2 +- remove-nth-node-from-end-of-list/index.md | 2 +- reorder-list/index.md | 2 +- restore-ip-addresses/index.md | 2 +- reverse-integer/index.md | 2 +- reverse-linked-list-ii/index.md | 2 +- reverse-nodes-in-k-group/index.md | 2 +- reverse-words-in-a-string/index.md | 2 +- roman-to-integer/index.md | 2 +- rotate-image/index.md | 2 +- rotate-list/index.md | 2 +- same-tree/index.md | 2 +- scramble-string/index.md | 2 +- search-a-2d-matrix/index.md | 2 +- search-for-a-range/index.md | 2 +- search-in-rotated-sorted-array-ii/index.md | 2 +- search-in-rotated-sorted-array/index.md | 2 +- search-insert-position/index.md | 2 +- set-matrix-zeroes/index.md | 2 +- simplify-path/index.md | 2 +- single-number-ii/index.md | 2 +- single-number/index.md | 2 +- sort-colors/index.md | 2 +- sort-list/index.md | 2 +- spiral-matrix-ii/index.md | 2 +- spiral-matrix/index.md | 2 +- sqrtx/index.md | 2 +- string-to-integer-atoi/index.md | 2 +- subsets-ii/index.md | 2 +- subsets/index.md | 2 +- substring-with-concatenation-of-all-words/index.md | 2 +- sudoku-solver/index.md | 2 +- sum-root-to-leaf-numbers/index.md | 2 +- surrounded-regions/index.md | 2 +- swap-nodes-in-pairs/index.md | 2 +- symmetric-tree/index.md | 2 +- text-justification/index.md | 2 +- trapping-rain-water/index.md | 2 +- triangle/index.md | 2 +- two-sum/index.md | 2 +- unique-binary-search-trees-ii/index.md | 2 +- unique-binary-search-trees/index.md | 2 +- unique-paths-ii/index.md | 2 +- unique-paths/index.md | 2 +- valid-number/index.md | 2 +- valid-palindrome/index.md | 2 +- valid-parentheses/index.md | 2 +- valid-sudoku/index.md | 2 +- validate-binary-search-tree/index.md | 2 +- wildcard-matching/index.md | 2 +- word-break-ii/index.md | 2 +- word-break/index.md | 2 +- word-ladder-ii/index.md | 2 +- word-ladder/index.md | 2 +- word-search/index.md | 2 +- zigzag-conversion/index.md | 2 +- 163 files changed, 163 insertions(+), 163 deletions(-) diff --git a/3sum-closest/index.md b/3sum-closest/index.md index ab96981..b002b14 100644 --- a/3sum-closest/index.md +++ b/3sum-closest/index.md @@ -1,7 +1,7 @@ --- layout: solution title: 3Sum Closest -date: 2014-08-02 23:07:51 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 16 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/3sum/index.md b/3sum/index.md index 2094319..16827d0 100644 --- a/3sum/index.md +++ b/3sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: 3Sum -date: 2014-08-02 23:02:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 15 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/4sum/index.md b/4sum/index.md index 0129bf0..525eb28 100644 --- a/4sum/index.md +++ b/4sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: 4Sum -date: 2014-08-02 23:43:08 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 18 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/add-binary/index.md b/add-binary/index.md index a6100c8..1739a6a 100644 --- a/add-binary/index.md +++ b/add-binary/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Add Binary -date: 2014-08-02 20:24:48 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 67 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/add-two-numbers/index.md b/add-two-numbers/index.md index d534514..1c974fd 100644 --- a/add-two-numbers/index.md +++ b/add-two-numbers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Add Two Numbers -date: 2014-08-02 20:31:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 2 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/anagrams/index.md b/anagrams/index.md index 242d1b7..3a959e4 100644 --- a/anagrams/index.md +++ b/anagrams/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Anagrams -date: 2014-07-26 18:47:25 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 49 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/balanced-binary-tree/index.md b/balanced-binary-tree/index.md index 4012030..3ad8f6a 100644 --- a/balanced-binary-tree/index.md +++ b/balanced-binary-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Balanced Binary Tree -date: 2014-07-25 01:13:33 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 110 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/best-time-to-buy-and-sell-stock-ii/index.md b/best-time-to-buy-and-sell-stock-ii/index.md index df67efa..f784aca 100644 --- a/best-time-to-buy-and-sell-stock-ii/index.md +++ b/best-time-to-buy-and-sell-stock-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Best Time to Buy and Sell Stock II -date: 2014-07-30 23:47:55 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 122 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/best-time-to-buy-and-sell-stock-iii/index.md b/best-time-to-buy-and-sell-stock-iii/index.md index bf69cc9..20c985e 100644 --- a/best-time-to-buy-and-sell-stock-iii/index.md +++ b/best-time-to-buy-and-sell-stock-iii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Best Time to Buy and Sell Stock III -date: 2014-08-03 08:26:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 123 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/best-time-to-buy-and-sell-stock/index.md b/best-time-to-buy-and-sell-stock/index.md index cfbb401..1489be2 100644 --- a/best-time-to-buy-and-sell-stock/index.md +++ b/best-time-to-buy-and-sell-stock/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Best Time to Buy and Sell Stock -date: 2014-07-30 00:42:07 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 121 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-search-tree-iterator/index.md b/binary-search-tree-iterator/index.md index 46925ee..ba5bedb 100644 --- a/binary-search-tree-iterator/index.md +++ b/binary-search-tree-iterator/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Search Tree Iterator -date: 2014-12-31 16:13:14+08:00 +date: 2014-12-31 16:16:36 +0800 leetcode_id: 173 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-inorder-traversal/index.md b/binary-tree-inorder-traversal/index.md index 3a1d9fd..db33f61 100644 --- a/binary-tree-inorder-traversal/index.md +++ b/binary-tree-inorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Inorder Traversal -date: 2014-07-28 01:06:09 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 94 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-level-order-traversal-ii/index.md b/binary-tree-level-order-traversal-ii/index.md index 9e09530..fe6ac33 100644 --- a/binary-tree-level-order-traversal-ii/index.md +++ b/binary-tree-level-order-traversal-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Level Order Traversal II -date: 2014-08-01 19:04:31 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 107 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-level-order-traversal/index.md b/binary-tree-level-order-traversal/index.md index 72fedf7..ad1f022 100644 --- a/binary-tree-level-order-traversal/index.md +++ b/binary-tree-level-order-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Level Order Traversal -date: 2014-08-01 17:34:15 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 102 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-maximum-path-sum/index.md b/binary-tree-maximum-path-sum/index.md index 4f2df61..bc62599 100644 --- a/binary-tree-maximum-path-sum/index.md +++ b/binary-tree-maximum-path-sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Maximum Path Sum -date: 2014-08-12 18:28:08 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 124 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-postorder-traversal/index.md b/binary-tree-postorder-traversal/index.md index b9714cb..fb76b55 100644 --- a/binary-tree-postorder-traversal/index.md +++ b/binary-tree-postorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Postorder Traversal -date: 2014-07-30 01:19:00 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 145 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-preorder-traversal/index.md b/binary-tree-preorder-traversal/index.md index 0db5728..e7e8dc4 100644 --- a/binary-tree-preorder-traversal/index.md +++ b/binary-tree-preorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Preorder Traversal -date: 2014-07-30 01:18:02 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 144 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/binary-tree-zigzag-level-order-traversal/index.md b/binary-tree-zigzag-level-order-traversal/index.md index 3786b46..5fc8762 100644 --- a/binary-tree-zigzag-level-order-traversal/index.md +++ b/binary-tree-zigzag-level-order-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Zigzag Level Order Traversal -date: 2014-08-06 20:53:54 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 103 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/candy/index.md b/candy/index.md index 68c2224..b78c5d6 100644 --- a/candy/index.md +++ b/candy/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Candy -date: 2014-08-01 14:53:22 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 135 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/climbing-stairs/index.md b/climbing-stairs/index.md index c16e4d7..d6a084e 100644 --- a/climbing-stairs/index.md +++ b/climbing-stairs/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Climbing Stairs -date: 2014-07-29 15:10:41 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 70 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/clone-graph/index.md b/clone-graph/index.md index 7eb9060..f98f6fe 100644 --- a/clone-graph/index.md +++ b/clone-graph/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Clone Graph -date: 2014-07-25 18:53:55 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 133 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/combination-sum-ii/index.md b/combination-sum-ii/index.md index de86bf4..5e1d25e 100644 --- a/combination-sum-ii/index.md +++ b/combination-sum-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Combination Sum II -date: 2014-08-13 18:00:07 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 40 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/combination-sum/index.md b/combination-sum/index.md index 9b9f9ea..7f3a9ae 100644 --- a/combination-sum/index.md +++ b/combination-sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Combination Sum -date: 2014-08-13 17:57:39 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 39 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/combinations/index.md b/combinations/index.md index 1ed4036..175a482 100644 --- a/combinations/index.md +++ b/combinations/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Combinations -date: 2014-08-07 22:09:22 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 77 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md index c644936..7247604 100644 --- a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md +++ b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Construct Binary Tree from Inorder and Postorder Traversal -date: 2014-08-12 19:03:53 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 106 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md index bced3c4..d7037b3 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Construct Binary Tree from Preorder and Inorder Traversal -date: 2014-08-12 18:59:20 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 105 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/container-with-most-water/index.md b/container-with-most-water/index.md index a9ee683..06de669 100644 --- a/container-with-most-water/index.md +++ b/container-with-most-water/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Container With Most Water -date: 2014-08-04 14:16:13 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 11 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/convert-sorted-array-to-binary-search-tree/index.md b/convert-sorted-array-to-binary-search-tree/index.md index aed8e38..e6dee32 100644 --- a/convert-sorted-array-to-binary-search-tree/index.md +++ b/convert-sorted-array-to-binary-search-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Convert Sorted Array to Binary Search Tree -date: 2014-08-02 20:48:40 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 108 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/convert-sorted-list-to-binary-search-tree/index.md b/convert-sorted-list-to-binary-search-tree/index.md index 65960aa..dd62fa9 100644 --- a/convert-sorted-list-to-binary-search-tree/index.md +++ b/convert-sorted-list-to-binary-search-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Convert Sorted List to Binary Search Tree -date: 2014-08-03 00:44:50 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 109 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/copy-list-with-random-pointer/index.md b/copy-list-with-random-pointer/index.md index 76495fe..78f85e1 100644 --- a/copy-list-with-random-pointer/index.md +++ b/copy-list-with-random-pointer/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Copy List with Random Pointer -date: 2014-08-01 18:11:42 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 138 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/count-and-say/index.md b/count-and-say/index.md index ae9d2d7..555c64e 100644 --- a/count-and-say/index.md +++ b/count-and-say/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Count and Say -date: 2014-07-26 18:50:47 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 38 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/decode-ways/index.md b/decode-ways/index.md index 6590566..6461d68 100644 --- a/decode-ways/index.md +++ b/decode-ways/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Decode Ways -date: 2014-08-01 11:16:28 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 91 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/distinct-subsequences/index.md b/distinct-subsequences/index.md index c6e7085..b1da625 100644 --- a/distinct-subsequences/index.md +++ b/distinct-subsequences/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Distinct Subsequences -date: 2014-08-28 01:16:24 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 115 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/divide-two-integers/index.md b/divide-two-integers/index.md index 515497b..c4b00cf 100644 --- a/divide-two-integers/index.md +++ b/divide-two-integers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Divide Two Integers -date: 2014-07-26 22:51:51 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 29 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/edit-distance/index.md b/edit-distance/index.md index 8475748..07ac2b6 100644 --- a/edit-distance/index.md +++ b/edit-distance/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Edit Distance -date: 2014-08-27 01:17:53 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 72 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/evaluate-reverse-polish-notation/index.md b/evaluate-reverse-polish-notation/index.md index 19cdfc8..664becc 100644 --- a/evaluate-reverse-polish-notation/index.md +++ b/evaluate-reverse-polish-notation/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Evaluate Reverse Polish Notation -date: 2014-08-02 20:57:09 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 150 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/factorial-trailing-zeroes/index.md b/factorial-trailing-zeroes/index.md index ffd0584..8fac0c3 100644 --- a/factorial-trailing-zeroes/index.md +++ b/factorial-trailing-zeroes/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Factorial Trailing Zeroes -date: 2014-12-30 18:00:00+08:00 +date: 2014-12-30 18:01:41 +0800 leetcode_id: 172 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/find-minimum-in-rotated-sorted-array-ii/index.md b/find-minimum-in-rotated-sorted-array-ii/index.md index a7191f6..ac995a8 100644 --- a/find-minimum-in-rotated-sorted-array-ii/index.md +++ b/find-minimum-in-rotated-sorted-array-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Find Minimum in Rotated Sorted Array II -date: 2014-10-21 13:50:45 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 154 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/find-minimum-in-rotated-sorted-array/index.md b/find-minimum-in-rotated-sorted-array/index.md index 93f9415..466d818 100644 --- a/find-minimum-in-rotated-sorted-array/index.md +++ b/find-minimum-in-rotated-sorted-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Find Minimum in Rotated Sorted Array -date: 2014-10-21 13:29:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 153 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/find-peak-element/index.md b/find-peak-element/index.md index 96b6acd..a88f70d 100644 --- a/find-peak-element/index.md +++ b/find-peak-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Find Peak Element -date: 2014-12-15 20:06:00 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 162 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/first-missing-positive/index.md b/first-missing-positive/index.md index 2035908..60d7cd5 100644 --- a/first-missing-positive/index.md +++ b/first-missing-positive/index.md @@ -1,7 +1,7 @@ --- layout: solution title: First Missing Positive -date: 2014-08-04 12:45:58 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 41 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/flatten-binary-tree-to-linked-list/index.md b/flatten-binary-tree-to-linked-list/index.md index 4700562..03c81ec 100644 --- a/flatten-binary-tree-to-linked-list/index.md +++ b/flatten-binary-tree-to-linked-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Flatten Binary Tree to Linked List -date: 2014-08-04 13:46:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 114 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/gas-station/index.md b/gas-station/index.md index 0d6b5a8..0f36f94 100644 --- a/gas-station/index.md +++ b/gas-station/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Gas Station -date: 2014-08-17 23:57:14 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 134 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/generate-parentheses/index.md b/generate-parentheses/index.md index dc0386d..0e86418 100644 --- a/generate-parentheses/index.md +++ b/generate-parentheses/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Generate Parentheses -date: 2014-08-12 16:58:24 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 22 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/gray-code/index.md b/gray-code/index.md index 1252617..7a25493 100644 --- a/gray-code/index.md +++ b/gray-code/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Gray Code -date: 2014-08-07 20:12:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 89 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/implement-strstr/index.md b/implement-strstr/index.md index c0a2fb9..193d19d 100644 --- a/implement-strstr/index.md +++ b/implement-strstr/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Implement strStr() -date: 2014-07-24 23:50:24 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 28 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/insert-interval/index.md b/insert-interval/index.md index 4d9e99b..373a916 100644 --- a/insert-interval/index.md +++ b/insert-interval/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Insert Interval -date: 2014-07-31 00:15:25 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 57 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/insertion-sort-list/index.md b/insertion-sort-list/index.md index f7a1cc6..dd80efc 100644 --- a/insertion-sort-list/index.md +++ b/insertion-sort-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Insertion Sort List -date: 2014-08-06 10:22:40 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 147 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/integer-to-roman/index.md b/integer-to-roman/index.md index ea56551..8247fb7 100644 --- a/integer-to-roman/index.md +++ b/integer-to-roman/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Integer to Roman -date: 2014-08-07 17:11:23 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 12 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/interleaving-string/index.md b/interleaving-string/index.md index 8204a70..b02643e 100644 --- a/interleaving-string/index.md +++ b/interleaving-string/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Interleaving String -date: 2014-08-06 11:48:41 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 97 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/intersection-of-two-linked-lists/index.md b/intersection-of-two-linked-lists/index.md index 1f950ae..8b96b46 100644 --- a/intersection-of-two-linked-lists/index.md +++ b/intersection-of-two-linked-lists/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Intersection of Two Linked Lists -date: 2014-12-15 18:23:24 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 160 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/jump-game-ii/index.md b/jump-game-ii/index.md index 15409aa..0dcabcf 100644 --- a/jump-game-ii/index.md +++ b/jump-game-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Jump Game II -date: 2014-08-05 23:31:47 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 45 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/jump-game/index.md b/jump-game/index.md index cc09a9d..a85e7aa 100644 --- a/jump-game/index.md +++ b/jump-game/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Jump Game -date: 2014-07-23 18:48:31 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 55 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/largest-rectangle-in-histogram/index.md b/largest-rectangle-in-histogram/index.md index 5eb25fd..0fe1e19 100644 --- a/largest-rectangle-in-histogram/index.md +++ b/largest-rectangle-in-histogram/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Largest Rectangle in Histogram -date: 2014-07-30 17:01:27 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 84 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/length-of-last-word/index.md b/length-of-last-word/index.md index 989eaea..b7075e0 100644 --- a/length-of-last-word/index.md +++ b/length-of-last-word/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Length of Last Word -date: 2014-08-04 14:46:58 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 58 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/letter-combinations-of-a-phone-number/index.md b/letter-combinations-of-a-phone-number/index.md index d59ebbd..63f2cf0 100644 --- a/letter-combinations-of-a-phone-number/index.md +++ b/letter-combinations-of-a-phone-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Letter Combinations of a Phone Number -date: 2014-07-26 23:35:47 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 17 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/linked-list-cycle-ii/index.md b/linked-list-cycle-ii/index.md index 7c63e2c..e872762 100644 --- a/linked-list-cycle-ii/index.md +++ b/linked-list-cycle-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Linked List Cycle II -date: 2014-07-30 17:54:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 142 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/linked-list-cycle/index.md b/linked-list-cycle/index.md index 9b61c53..7829596 100644 --- a/linked-list-cycle/index.md +++ b/linked-list-cycle/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Linked List Cycle -date: 2014-07-27 18:20:47 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 141 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-common-prefix/index.md b/longest-common-prefix/index.md index d4313f0..78fc4f3 100644 --- a/longest-common-prefix/index.md +++ b/longest-common-prefix/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Common Prefix -date: 2014-08-01 17:49:20 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 14 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-consecutive-sequence/index.md b/longest-consecutive-sequence/index.md index 212eeab..5553e49 100644 --- a/longest-consecutive-sequence/index.md +++ b/longest-consecutive-sequence/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Consecutive Sequence -date: 2014-08-07 20:07:11 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 128 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-palindromic-substring/index.md b/longest-palindromic-substring/index.md index 3a97fa6..2f5b645 100644 --- a/longest-palindromic-substring/index.md +++ b/longest-palindromic-substring/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Palindromic Substring -date: 2014-08-18 17:56:19 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 5 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-substring-with-at-most-two-distinct-characters/index.md b/longest-substring-with-at-most-two-distinct-characters/index.md index e87fff0..c1b808a 100644 --- a/longest-substring-with-at-most-two-distinct-characters/index.md +++ b/longest-substring-with-at-most-two-distinct-characters/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Substring with At Most Two Distinct Characters -date: 2014-12-15 18:13:21 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 159 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-substring-without-repeating-characters/index.md b/longest-substring-without-repeating-characters/index.md index 90804a8..868db91 100644 --- a/longest-substring-without-repeating-characters/index.md +++ b/longest-substring-without-repeating-characters/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Substring Without Repeating Characters -date: 2014-08-12 00:32:47 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 3 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/longest-valid-parentheses/index.md b/longest-valid-parentheses/index.md index 0b037f3..b010d76 100644 --- a/longest-valid-parentheses/index.md +++ b/longest-valid-parentheses/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Longest Valid Parentheses -date: 2014-08-12 17:28:23 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 32 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/lru-cache/index.md b/lru-cache/index.md index 07c531f..3197346 100644 --- a/lru-cache/index.md +++ b/lru-cache/index.md @@ -1,7 +1,7 @@ --- layout: solution title: LRU Cache -date: 2014-07-28 01:06:09 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 146 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/max-points-on-a-line/index.md b/max-points-on-a-line/index.md index fa12cdb..b237c67 100644 --- a/max-points-on-a-line/index.md +++ b/max-points-on-a-line/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Max Points on a Line -date: 2014-07-25 12:40:38 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 149 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/maximal-rectangle/index.md b/maximal-rectangle/index.md index 8c4b561..c04459b 100644 --- a/maximal-rectangle/index.md +++ b/maximal-rectangle/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximal Rectangle -date: 2014-08-03 09:01:30 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 85 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/maximum-depth-of-binary-tree/index.md b/maximum-depth-of-binary-tree/index.md index ac93068..6b3b4c2 100644 --- a/maximum-depth-of-binary-tree/index.md +++ b/maximum-depth-of-binary-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Depth of Binary Tree -date: 2014-08-01 01:25:55 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 104 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/maximum-gap/index.md b/maximum-gap/index.md index b1cc59b..b87796f 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Gap -date: 2014-12-16 01:13:52 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 164 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/maximum-subarray/index.md b/maximum-subarray/index.md index 3546216..e91f5a3 100644 --- a/maximum-subarray/index.md +++ b/maximum-subarray/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Maximum Subarray -date: 2014-08-07 14:22:53 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 53 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/median-of-two-sorted-arrays/index.md b/median-of-two-sorted-arrays/index.md index 1070f61..8c294ec 100644 --- a/median-of-two-sorted-arrays/index.md +++ b/median-of-two-sorted-arrays/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Median of Two Sorted Arrays -date: 2014-08-11 19:38:54 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 4 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/merge-intervals/index.md b/merge-intervals/index.md index bef0a8c..59998c2 100644 --- a/merge-intervals/index.md +++ b/merge-intervals/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Merge Intervals -date: 2014-07-29 16:56:39 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 56 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/merge-k-sorted-lists/index.md b/merge-k-sorted-lists/index.md index 2c5aa24..756ff07 100644 --- a/merge-k-sorted-lists/index.md +++ b/merge-k-sorted-lists/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Merge k Sorted Lists -date: 2014-07-30 19:13:09 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 23 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/merge-sorted-array/index.md b/merge-sorted-array/index.md index 92af976..adf43fc 100644 --- a/merge-sorted-array/index.md +++ b/merge-sorted-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Merge Sorted Array -date: 2014-07-24 18:38:41 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 88 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/merge-two-sorted-lists/index.md b/merge-two-sorted-lists/index.md index 4630687..15358d2 100644 --- a/merge-two-sorted-lists/index.md +++ b/merge-two-sorted-lists/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Merge Two Sorted Lists -date: 2014-07-30 18:58:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 21 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/minimum-depth-of-binary-tree/index.md b/minimum-depth-of-binary-tree/index.md index 3a1689b..f97d54f 100644 --- a/minimum-depth-of-binary-tree/index.md +++ b/minimum-depth-of-binary-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Minimum Depth of Binary Tree -date: 2014-08-01 01:24:15 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 111 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/minimum-path-sum/index.md b/minimum-path-sum/index.md index b51af34..0ad9aac 100644 --- a/minimum-path-sum/index.md +++ b/minimum-path-sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Minimum Path Sum -date: 2014-08-06 00:58:46 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 64 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/minimum-window-substring/index.md b/minimum-window-substring/index.md index 9ede576..ee153da 100644 --- a/minimum-window-substring/index.md +++ b/minimum-window-substring/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Minimum Window Substring -date: 2014-08-25 00:31:17 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 76 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/missing-ranges/index.md b/missing-ranges/index.md index 6cc5240..3a15aa8 100644 --- a/missing-ranges/index.md +++ b/missing-ranges/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Missing Ranges -date: 2014-12-16 00:23:40 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 163 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/multiply-strings/index.md b/multiply-strings/index.md index e25a785..d23bae4 100644 --- a/multiply-strings/index.md +++ b/multiply-strings/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Multiply Strings -date: 2014-08-02 20:38:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 43 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/n-queens-ii/index.md b/n-queens-ii/index.md index d79ab36..aa106c3 100644 --- a/n-queens-ii/index.md +++ b/n-queens-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: N-Queens II -date: 2014-07-31 18:58:00 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 52 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/n-queens/index.md b/n-queens/index.md index 31f72f7..979bab5 100644 --- a/n-queens/index.md +++ b/n-queens/index.md @@ -1,7 +1,7 @@ --- layout: solution title: N-Queens -date: 2014-08-01 01:00:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 51 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/next-permutation/index.md b/next-permutation/index.md index 5eac976..2484374 100644 --- a/next-permutation/index.md +++ b/next-permutation/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Next Permutation -date: 2014-08-31 00:42:19 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 31 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/one-edit-distance/index.md b/one-edit-distance/index.md index 21422d7..ff2ebd1 100644 --- a/one-edit-distance/index.md +++ b/one-edit-distance/index.md @@ -1,7 +1,7 @@ --- layout: solution title: One Edit Distance -date: 2014-12-15 18:35:04 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 161 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/palindrome-number/index.md b/palindrome-number/index.md index c54cc43..4f0cb66 100644 --- a/palindrome-number/index.md +++ b/palindrome-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Palindrome Number -date: 2014-07-31 22:24:16 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 9 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/palindrome-partitioning-ii/index.md b/palindrome-partitioning-ii/index.md index 9106cd7..92c6d4e 100644 --- a/palindrome-partitioning-ii/index.md +++ b/palindrome-partitioning-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Palindrome Partitioning II -date: 2014-08-22 20:14:10 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 132 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/palindrome-partitioning/index.md b/palindrome-partitioning/index.md index 5009fb9..167101f 100644 --- a/palindrome-partitioning/index.md +++ b/palindrome-partitioning/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Palindrome Partitioning -date: 2014-08-18 23:49:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 131 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/partition-list/index.md b/partition-list/index.md index 3211dfe..348fba0 100644 --- a/partition-list/index.md +++ b/partition-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Partition List -date: 2014-07-31 15:09:14 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 86 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/pascals-triangle-ii/index.md b/pascals-triangle-ii/index.md index 1144559..e7573fe 100644 --- a/pascals-triangle-ii/index.md +++ b/pascals-triangle-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Pascal's Triangle II -date: 2014-07-30 11:39:03 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 119 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/pascals-triangle/index.md b/pascals-triangle/index.md index a7e3879..c9b49ef 100644 --- a/pascals-triangle/index.md +++ b/pascals-triangle/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Pascal's Triangle -date: 2014-07-30 00:12:08 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 118 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/path-sum-ii/index.md b/path-sum-ii/index.md index ce7a453..1bb6614 100644 --- a/path-sum-ii/index.md +++ b/path-sum-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Path Sum II -date: 2014-08-06 18:23:30 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 113 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/path-sum/index.md b/path-sum/index.md index 41a95a0..73781f3 100644 --- a/path-sum/index.md +++ b/path-sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Path Sum -date: 2014-08-02 01:01:57 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 112 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/permutation-sequence/index.md b/permutation-sequence/index.md index 2e8756c..1956c27 100644 --- a/permutation-sequence/index.md +++ b/permutation-sequence/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Permutation Sequence -date: 2014-08-29 20:57:36 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 60 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/permutations-ii/index.md b/permutations-ii/index.md index 1aa0254..c81f239 100644 --- a/permutations-ii/index.md +++ b/permutations-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Permutations II -date: 2014-08-31 00:52:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 47 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/permutations/index.md b/permutations/index.md index 0f3262d..6b9e57c 100644 --- a/permutations/index.md +++ b/permutations/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Permutations -date: 2014-08-17 23:07:06 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 46 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/plus-one/index.md b/plus-one/index.md index f071ac7..e04f238 100644 --- a/plus-one/index.md +++ b/plus-one/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Plus One -date: 2014-08-02 19:53:52 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 66 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/populating-next-right-pointers-in-each-node-ii/index.md b/populating-next-right-pointers-in-each-node-ii/index.md index fa6f520..262be19 100644 --- a/populating-next-right-pointers-in-each-node-ii/index.md +++ b/populating-next-right-pointers-in-each-node-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Populating Next Right Pointers in Each Node II -date: 2014-08-20 17:35:02 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 117 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/populating-next-right-pointers-in-each-node/index.md b/populating-next-right-pointers-in-each-node/index.md index 9060bbd..da292c2 100644 --- a/populating-next-right-pointers-in-each-node/index.md +++ b/populating-next-right-pointers-in-each-node/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Populating Next Right Pointers in Each Node -date: 2014-08-20 16:49:17 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 116 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/powx-n/index.md b/powx-n/index.md index 05b1ab7..3abcfb9 100644 --- a/powx-n/index.md +++ b/powx-n/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Pow(x, n) -date: 2014-07-24 18:26:54 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 50 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/read-n-characters-given-read4-ii-call-multiple-times/index.md b/read-n-characters-given-read4-ii-call-multiple-times/index.md index e4c494b..cc2df63 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/index.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Read N Characters Given Read4 II - Call multiple times -date: 2014-12-15 17:32:05 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 158 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/read-n-characters-given-read4/index.md b/read-n-characters-given-read4/index.md index 7192f97..19a4f5e 100644 --- a/read-n-characters-given-read4/index.md +++ b/read-n-characters-given-read4/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Read N Characters Given Read4 -date: 2014-12-15 17:18:30 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 157 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/recover-binary-search-tree/index.md b/recover-binary-search-tree/index.md index b368c31..52ba332 100644 --- a/recover-binary-search-tree/index.md +++ b/recover-binary-search-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Recover Binary Search Tree -date: 2014-08-01 18:35:38 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 99 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/regular-expression-matching/index.md b/regular-expression-matching/index.md index cd4f16a..309dc29 100644 --- a/regular-expression-matching/index.md +++ b/regular-expression-matching/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Regular Expression Matching -date: 2014-08-02 02:43:26 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 10 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-duplicates-from-sorted-array-ii/index.md b/remove-duplicates-from-sorted-array-ii/index.md index a912e8e..e1f66e9 100644 --- a/remove-duplicates-from-sorted-array-ii/index.md +++ b/remove-duplicates-from-sorted-array-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Duplicates from Sorted Array II -date: 2014-08-04 14:24:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 80 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-duplicates-from-sorted-array/index.md b/remove-duplicates-from-sorted-array/index.md index 825969c..4393d88 100644 --- a/remove-duplicates-from-sorted-array/index.md +++ b/remove-duplicates-from-sorted-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Duplicates from Sorted Array -date: 2014-08-04 14:06:11 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 26 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-duplicates-from-sorted-list-ii/index.md b/remove-duplicates-from-sorted-list-ii/index.md index 8eca73d..4d64ac1 100644 --- a/remove-duplicates-from-sorted-list-ii/index.md +++ b/remove-duplicates-from-sorted-list-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Duplicates from Sorted List II -date: 2014-08-04 14:37:56 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 82 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-duplicates-from-sorted-list/index.md b/remove-duplicates-from-sorted-list/index.md index faf9f36..dbe930c 100644 --- a/remove-duplicates-from-sorted-list/index.md +++ b/remove-duplicates-from-sorted-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Duplicates from Sorted List -date: 2014-08-04 14:37:45 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 83 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-element/index.md b/remove-element/index.md index dd2c3de..e868ba8 100644 --- a/remove-element/index.md +++ b/remove-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Element -date: 2014-07-31 15:57:51 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 27 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/remove-nth-node-from-end-of-list/index.md b/remove-nth-node-from-end-of-list/index.md index 41cdb30..fb3fa2e 100644 --- a/remove-nth-node-from-end-of-list/index.md +++ b/remove-nth-node-from-end-of-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Nth Node From End of List -date: 2014-08-04 14:44:23 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 19 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reorder-list/index.md b/reorder-list/index.md index 2ee4590..0d40da5 100644 --- a/reorder-list/index.md +++ b/reorder-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reorder List -date: 2014-07-29 15:26:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 143 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/restore-ip-addresses/index.md b/restore-ip-addresses/index.md index d8b761d..36710a2 100644 --- a/restore-ip-addresses/index.md +++ b/restore-ip-addresses/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Restore IP Addresses -date: 2014-08-01 18:53:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 93 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-integer/index.md b/reverse-integer/index.md index 9ec66df..4cd0a35 100644 --- a/reverse-integer/index.md +++ b/reverse-integer/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Integer -date: 2014-08-04 13:40:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 7 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-linked-list-ii/index.md b/reverse-linked-list-ii/index.md index d6f4bd4..d65f42e 100644 --- a/reverse-linked-list-ii/index.md +++ b/reverse-linked-list-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Linked List II -date: 2014-08-04 15:17:26 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 92 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-nodes-in-k-group/index.md b/reverse-nodes-in-k-group/index.md index 9a520e8..b034ef5 100644 --- a/reverse-nodes-in-k-group/index.md +++ b/reverse-nodes-in-k-group/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Nodes in k-Group -date: 2014-08-04 15:23:50 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 25 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-words-in-a-string/index.md b/reverse-words-in-a-string/index.md index fd90697..0de130d 100644 --- a/reverse-words-in-a-string/index.md +++ b/reverse-words-in-a-string/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Words in a String -date: 2014-08-01 14:19:34 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 151 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/roman-to-integer/index.md b/roman-to-integer/index.md index f8bbe11..d99b286 100644 --- a/roman-to-integer/index.md +++ b/roman-to-integer/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Roman to Integer -date: 2014-07-31 13:56:29 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 13 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/rotate-image/index.md b/rotate-image/index.md index a9398d9..f8a2719 100644 --- a/rotate-image/index.md +++ b/rotate-image/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Rotate Image -date: 2014-08-28 16:12:56 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 48 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/rotate-list/index.md b/rotate-list/index.md index 18d5da1..45258b7 100644 --- a/rotate-list/index.md +++ b/rotate-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Rotate List -date: 2014-08-04 15:10:53 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 61 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/same-tree/index.md b/same-tree/index.md index 4b9b2f7..b782b27 100644 --- a/same-tree/index.md +++ b/same-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Same Tree -date: 2014-07-23 18:53:33 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 100 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/scramble-string/index.md b/scramble-string/index.md index 0c656fd..d53fff5 100644 --- a/scramble-string/index.md +++ b/scramble-string/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Scramble String -date: 2014-07-24 19:07:16 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 87 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/search-a-2d-matrix/index.md b/search-a-2d-matrix/index.md index 2822a2b..daf935f 100644 --- a/search-a-2d-matrix/index.md +++ b/search-a-2d-matrix/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Search a 2D Matrix -date: 2014-08-04 13:33:58 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 74 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/search-for-a-range/index.md b/search-for-a-range/index.md index 4c5c7c5..dd9c71b 100644 --- a/search-for-a-range/index.md +++ b/search-for-a-range/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Search for a Range -date: 2014-07-27 00:31:27 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 34 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/search-in-rotated-sorted-array-ii/index.md b/search-in-rotated-sorted-array-ii/index.md index 1e616e4..8139bb6 100644 --- a/search-in-rotated-sorted-array-ii/index.md +++ b/search-in-rotated-sorted-array-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Search in Rotated Sorted Array II -date: 2014-08-02 21:27:14 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 81 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/search-in-rotated-sorted-array/index.md b/search-in-rotated-sorted-array/index.md index 5a02627..2215282 100644 --- a/search-in-rotated-sorted-array/index.md +++ b/search-in-rotated-sorted-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Search in Rotated Sorted Array -date: 2014-07-29 19:03:11 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 33 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/search-insert-position/index.md b/search-insert-position/index.md index c24c1aa..303314f 100644 --- a/search-insert-position/index.md +++ b/search-insert-position/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Search Insert Position -date: 2014-07-31 00:22:36 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 35 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/set-matrix-zeroes/index.md b/set-matrix-zeroes/index.md index 3ef92a1..ab5f6ca 100644 --- a/set-matrix-zeroes/index.md +++ b/set-matrix-zeroes/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Set Matrix Zeroes -date: 2014-08-01 16:21:17 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 73 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/simplify-path/index.md b/simplify-path/index.md index d4996dc..5a984c4 100644 --- a/simplify-path/index.md +++ b/simplify-path/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Simplify Path -date: 2014-08-02 23:57:16 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 71 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/single-number-ii/index.md b/single-number-ii/index.md index d2735c9..49a8ae8 100644 --- a/single-number-ii/index.md +++ b/single-number-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Single Number II -date: 2014-08-04 15:03:21 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 137 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/single-number/index.md b/single-number/index.md index bc67c6e..8f9175d 100644 --- a/single-number/index.md +++ b/single-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Single Number -date: 2014-07-26 23:49:23 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 136 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sort-colors/index.md b/sort-colors/index.md index 0f59c8b..289bdca 100644 --- a/sort-colors/index.md +++ b/sort-colors/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sort Colors -date: 2014-07-29 14:23:45 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 75 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sort-list/index.md b/sort-list/index.md index 6809a8d..f6ac98d 100644 --- a/sort-list/index.md +++ b/sort-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sort List -date: 2014-07-30 22:43:55 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 148 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/spiral-matrix-ii/index.md b/spiral-matrix-ii/index.md index 2a731bb..fa9813a 100644 --- a/spiral-matrix-ii/index.md +++ b/spiral-matrix-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Spiral Matrix II -date: 2014-08-01 19:10:34 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 59 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/spiral-matrix/index.md b/spiral-matrix/index.md index e1e0403..99c8006 100644 --- a/spiral-matrix/index.md +++ b/spiral-matrix/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Spiral Matrix -date: 2014-08-01 19:06:55 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 54 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sqrtx/index.md b/sqrtx/index.md index 1e0efb1..2ef4d1a 100644 --- a/sqrtx/index.md +++ b/sqrtx/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sqrt(x) -date: 2014-08-12 12:20:49 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 69 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/string-to-integer-atoi/index.md b/string-to-integer-atoi/index.md index 708cb72..70484c6 100644 --- a/string-to-integer-atoi/index.md +++ b/string-to-integer-atoi/index.md @@ -1,7 +1,7 @@ --- layout: solution title: String to Integer (atoi) -date: 2014-07-27 00:43:11 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 8 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/subsets-ii/index.md b/subsets-ii/index.md index 32220dc..59c9588 100644 --- a/subsets-ii/index.md +++ b/subsets-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Subsets II -date: 2014-07-31 15:32:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 90 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/subsets/index.md b/subsets/index.md index f7e2e6b..1cb378e 100644 --- a/subsets/index.md +++ b/subsets/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Subsets -date: 2014-07-28 01:56:28 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 78 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/substring-with-concatenation-of-all-words/index.md b/substring-with-concatenation-of-all-words/index.md index df1d31c..3827ff6 100644 --- a/substring-with-concatenation-of-all-words/index.md +++ b/substring-with-concatenation-of-all-words/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Substring with Concatenation of All Words -date: 2014-08-23 00:06:08 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 30 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sudoku-solver/index.md b/sudoku-solver/index.md index 92ee7a7..533f205 100644 --- a/sudoku-solver/index.md +++ b/sudoku-solver/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sudoku Solver -date: 2014-08-01 00:53:53 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 37 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sum-root-to-leaf-numbers/index.md b/sum-root-to-leaf-numbers/index.md index 7730daf..c9923d3 100644 --- a/sum-root-to-leaf-numbers/index.md +++ b/sum-root-to-leaf-numbers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sum Root to Leaf Numbers -date: 2014-08-05 10:45:00 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 129 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/surrounded-regions/index.md b/surrounded-regions/index.md index 805f27e..0cabbe2 100644 --- a/surrounded-regions/index.md +++ b/surrounded-regions/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Surrounded Regions -date: 2014-08-12 00:13:39 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 130 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/swap-nodes-in-pairs/index.md b/swap-nodes-in-pairs/index.md index 5b735c1..409f48c 100644 --- a/swap-nodes-in-pairs/index.md +++ b/swap-nodes-in-pairs/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Swap Nodes in Pairs -date: 2014-07-31 15:23:00 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 24 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/symmetric-tree/index.md b/symmetric-tree/index.md index 69185e9..cbce220 100644 --- a/symmetric-tree/index.md +++ b/symmetric-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Symmetric Tree -date: 2014-08-07 00:26:36 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 101 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/text-justification/index.md b/text-justification/index.md index 571561d..11f1826 100644 --- a/text-justification/index.md +++ b/text-justification/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Text Justification -date: 2014-07-31 00:28:22 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 68 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/trapping-rain-water/index.md b/trapping-rain-water/index.md index f138454..cfa47c3 100644 --- a/trapping-rain-water/index.md +++ b/trapping-rain-water/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Trapping Rain Water -date: 2014-07-29 01:15:56 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 42 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/triangle/index.md b/triangle/index.md index 0fc64a6..9a46f07 100644 --- a/triangle/index.md +++ b/triangle/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Triangle -date: 2014-07-27 00:21:38 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 120 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/two-sum/index.md b/two-sum/index.md index 32a97a7..c4e3e82 100644 --- a/two-sum/index.md +++ b/two-sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum -date: 2014-08-27 11:53:26 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 1 leetcode_id: 1 --- diff --git a/unique-binary-search-trees-ii/index.md b/unique-binary-search-trees-ii/index.md index 0f1accd..e6ab9be 100644 --- a/unique-binary-search-trees-ii/index.md +++ b/unique-binary-search-trees-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Unique Binary Search Trees II -date: 2014-08-12 01:15:29 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 95 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/unique-binary-search-trees/index.md b/unique-binary-search-trees/index.md index ffa7efe..b25c64f 100644 --- a/unique-binary-search-trees/index.md +++ b/unique-binary-search-trees/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Unique Binary Search Trees -date: 2014-08-12 01:11:10 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 96 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/unique-paths-ii/index.md b/unique-paths-ii/index.md index 798965c..124cfbe 100644 --- a/unique-paths-ii/index.md +++ b/unique-paths-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Unique Paths II -date: 2014-08-06 00:25:29 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 63 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/unique-paths/index.md b/unique-paths/index.md index c9db68c..33a3fc3 100644 --- a/unique-paths/index.md +++ b/unique-paths/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Unique Paths -date: 2014-08-06 00:07:04 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 62 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/valid-number/index.md b/valid-number/index.md index 8409e4e..9d189a4 100644 --- a/valid-number/index.md +++ b/valid-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Valid Number -date: 2014-08-01 11:33:18 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 65 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/valid-palindrome/index.md b/valid-palindrome/index.md index 2321401..69bfcac 100644 --- a/valid-palindrome/index.md +++ b/valid-palindrome/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Valid Palindrome -date: 2014-07-31 14:20:28 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 125 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/valid-parentheses/index.md b/valid-parentheses/index.md index 005548c..0a0e687 100644 --- a/valid-parentheses/index.md +++ b/valid-parentheses/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Valid Parentheses -date: 2014-07-30 00:01:04 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 20 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/valid-sudoku/index.md b/valid-sudoku/index.md index d6e750e..ff1e19f 100644 --- a/valid-sudoku/index.md +++ b/valid-sudoku/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Valid Sudoku -date: 2014-07-31 19:13:56 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 36 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/validate-binary-search-tree/index.md b/validate-binary-search-tree/index.md index 155241b..716ea48 100644 --- a/validate-binary-search-tree/index.md +++ b/validate-binary-search-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Validate Binary Search Tree -date: 2014-07-29 17:36:37 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 98 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/wildcard-matching/index.md b/wildcard-matching/index.md index 98111fa..7e5947e 100644 --- a/wildcard-matching/index.md +++ b/wildcard-matching/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Wildcard Matching -date: 2014-08-23 13:09:31 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 44 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/word-break-ii/index.md b/word-break-ii/index.md index c7bcb59..1f81e4d 100644 --- a/word-break-ii/index.md +++ b/word-break-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Break II -date: 2014-08-28 22:21:44 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 140 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/word-break/index.md b/word-break/index.md index 2bd847b..69f62cf 100644 --- a/word-break/index.md +++ b/word-break/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Break -date: 2014-08-20 19:53:59 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 139 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/word-ladder-ii/index.md b/word-ladder-ii/index.md index d3edf74..a76b3dd 100644 --- a/word-ladder-ii/index.md +++ b/word-ladder-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Ladder II -date: 2014-08-13 23:27:41 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 126 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/word-ladder/index.md b/word-ladder/index.md index fc67d42..9458dce 100644 --- a/word-ladder/index.md +++ b/word-ladder/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Ladder -date: 2014-08-13 18:48:36 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 127 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/word-search/index.md b/word-search/index.md index a0f4655..9ee737d 100644 --- a/word-search/index.md +++ b/word-search/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Search -date: 2014-08-07 17:23:40 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 79 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/zigzag-conversion/index.md b/zigzag-conversion/index.md index 19dff78..1778316 100644 --- a/zigzag-conversion/index.md +++ b/zigzag-conversion/index.md @@ -1,7 +1,7 @@ --- layout: solution title: ZigZag Conversion -date: 2014-07-31 14:06:32 +0800 +date: 2014-12-29 00:26:24 +0800 leetcode_id: 6 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 5823837577c44c8c23bac2a527886b6a641ecdde Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 31 Dec 2014 16:17:55 +0800 Subject: [PATCH 035/195] commit bst iter to gh-pages --- .../binary-search-tree-iterator/README.md | 0 .../binary-search-tree-iterator/Solution.java | 91 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 _includes/_root/binary-search-tree-iterator/README.md create mode 100644 _includes/_root/binary-search-tree-iterator/Solution.java diff --git a/_includes/_root/binary-search-tree-iterator/README.md b/_includes/_root/binary-search-tree-iterator/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/binary-search-tree-iterator/Solution.java b/_includes/_root/binary-search-tree-iterator/Solution.java new file mode 100644 index 0000000..5776345 --- /dev/null +++ b/_includes/_root/binary-search-tree-iterator/Solution.java @@ -0,0 +1,91 @@ +/** +* Definition for binary tree +* public class TreeNode { +* int val; +* TreeNode left; +* TreeNode right; +* TreeNode(int x) { val = x; } +* } +*/ + +public class BSTIterator { + + static enum ReturnAddress { + PRE, IN, POST, DONE; + } + + static class StackState { + ReturnAddress returnAddress = ReturnAddress.PRE; + TreeNode param; + + StackState(TreeNode param){ + this.param = param; + } + } + + Deque stack = new LinkedList(); + + public BSTIterator(TreeNode root) { + if(root != null) { + stack.push(new StackState(root)); + } + } + + /** @return whether we have a next smallest number */ + public boolean hasNext() { + if(!stack.isEmpty()){ + StackState current = stack.pop(); + switch(current.returnAddress){ + case PRE: + case IN: + stack.push(current); + return true; + + case POST: + if(current.param.right != null){ + stack.push(new StackState(current.param.right)); + return true; + } + } + return hasNext(); + } + return false; + } + + /** @return the next smallest number */ + public int next() { + + StackState current = stack.pop(); + switch(current.returnAddress){ + case PRE: + current.returnAddress = ReturnAddress.IN; + + if(current.param.left != null){ + stack.push(current); + stack.push(new StackState(current.param.left)); + break; + } + + case IN: + current.returnAddress = ReturnAddress.POST; + stack.push(current); + return current.param.val; + + case POST: + current.returnAddress = ReturnAddress.DONE; + + if(current.param.right != null){ + stack.push(current); + stack.push(new StackState(current.param.right)); + break; + } + } + return next(); + } +} + +/** +* Your BSTIterator will be called like this: +* BSTIterator i = new BSTIterator(root); +* while (i.hasNext()) v[f()] = i.next(); +*/ From ca1b13ab3fb8d7f90fdf23f0fd1bc94f47f61800 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 3 Jan 2015 03:26:48 +0800 Subject: [PATCH 036/195] add bst iter doc --- binary-search-tree-iterator/README.md | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/binary-search-tree-iterator/README.md b/binary-search-tree-iterator/README.md index e69de29..411fa1d 100644 --- a/binary-search-tree-iterator/README.md +++ b/binary-search-tree-iterator/README.md @@ -0,0 +1,43 @@ +## [Yielding](http://en.wikipedia.org/wiki/Generator_(computer_programming)) and [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal) + +In the problem [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), +we solved it by simlating the function call. + +Only a bit different this time, +when the caller calls `next()`: + + 1. just execute to next value returns + 1. save the stack and next address (state) + 1. yield the node value and return control to caller + +actions above is the `while` body part in the [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal). + +### Edge cases in `hasNext()` + +like [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), +when the stack is empty, there are no more nodes. + +However, if only one state left in the stack and the address of the state is `POST`, +we need some additional check. + +`POST` state here means to deal with right node of current node (value already yeild to caller when `IN` step). +sometimes, the node does not have right child. we should return false when caller ask `hasNext()`. + +## Why it is `O(h)` in space + +the space here used in my solution is the `stack`. +only tree nodes with left child will consume a space in the `stack`. +because nodes without left child can be yield to caller directly. + +Worst case + +``` + 1 + / + 2 + / + 3 +``` + +here we have to save `node 1` and `node 2` before we found `node 3`. +but the space used in stack will be no more than 3. From 86dd1cfa22a9a850462ac60781d88e643637961d Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 3 Jan 2015 03:36:44 +0800 Subject: [PATCH 037/195] add trailing zero doc --- factorial-trailing-zeroes/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/factorial-trailing-zeroes/README.md b/factorial-trailing-zeroes/README.md index e69de29..3f5e2b3 100644 --- a/factorial-trailing-zeroes/README.md +++ b/factorial-trailing-zeroes/README.md @@ -0,0 +1,11 @@ +## A trailing zero is made of factor 2 and factor 5 + +``` +n! = 2 ^ m * 5 ^ n * (other factors) +``` + +the count of trailing zero is `min(m, n)`. +because a `2` and a `5` generates a zero. + + +the work is just counting 2 and 5 ... From 6a7ddaf409ed696196118231ff6fe2ec1b730217 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 3 Jan 2015 03:53:03 +0800 Subject: [PATCH 038/195] add majority element doc --- majority-element/README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/majority-element/README.md b/majority-element/README.md index e69de29..69b0d60 100644 --- a/majority-element/README.md +++ b/majority-element/README.md @@ -0,0 +1,18 @@ +## [A Linear Time Majority Vote Algorithm](http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html) + +## Game: How to find 10 IPs which are flooding your server + +Imagine that there is an arena which can on only contains 10 people. +Every people is holding an IP. + +Now, throw the accessing IPs into the arena to hit the people with rule below: + + * a people is holding the same IP will get health `+1` + * if no people is holding the IP, the IP will hit a people randomly, that people's health `-1` + * people with health 0 will be kicked out of the arena and replace by new people hold current IP. + +at the end, people left in the arena with high health value are obviously the attackers. + + + + From 685233940b3a90bbd8d927b488e3a87879f52574 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 3 Jan 2015 03:54:02 +0800 Subject: [PATCH 039/195] commit 3 new docs to gh-pages --- .../binary-search-tree-iterator/README.md | 43 +++++++++++++++++++ .../_root/factorial-trailing-zeroes/README.md | 11 +++++ _includes/_root/majority-element/README.md | 18 ++++++++ binary-search-tree-iterator/index.md | 2 +- factorial-trailing-zeroes/index.md | 2 +- majority-element/index.md | 2 +- 6 files changed, 75 insertions(+), 3 deletions(-) diff --git a/_includes/_root/binary-search-tree-iterator/README.md b/_includes/_root/binary-search-tree-iterator/README.md index e69de29..411fa1d 100644 --- a/_includes/_root/binary-search-tree-iterator/README.md +++ b/_includes/_root/binary-search-tree-iterator/README.md @@ -0,0 +1,43 @@ +## [Yielding](http://en.wikipedia.org/wiki/Generator_(computer_programming)) and [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal) + +In the problem [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), +we solved it by simlating the function call. + +Only a bit different this time, +when the caller calls `next()`: + + 1. just execute to next value returns + 1. save the stack and next address (state) + 1. yield the node value and return control to caller + +actions above is the `while` body part in the [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal). + +### Edge cases in `hasNext()` + +like [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), +when the stack is empty, there are no more nodes. + +However, if only one state left in the stack and the address of the state is `POST`, +we need some additional check. + +`POST` state here means to deal with right node of current node (value already yeild to caller when `IN` step). +sometimes, the node does not have right child. we should return false when caller ask `hasNext()`. + +## Why it is `O(h)` in space + +the space here used in my solution is the `stack`. +only tree nodes with left child will consume a space in the `stack`. +because nodes without left child can be yield to caller directly. + +Worst case + +``` + 1 + / + 2 + / + 3 +``` + +here we have to save `node 1` and `node 2` before we found `node 3`. +but the space used in stack will be no more than 3. diff --git a/_includes/_root/factorial-trailing-zeroes/README.md b/_includes/_root/factorial-trailing-zeroes/README.md index e69de29..3f5e2b3 100644 --- a/_includes/_root/factorial-trailing-zeroes/README.md +++ b/_includes/_root/factorial-trailing-zeroes/README.md @@ -0,0 +1,11 @@ +## A trailing zero is made of factor 2 and factor 5 + +``` +n! = 2 ^ m * 5 ^ n * (other factors) +``` + +the count of trailing zero is `min(m, n)`. +because a `2` and a `5` generates a zero. + + +the work is just counting 2 and 5 ... diff --git a/_includes/_root/majority-element/README.md b/_includes/_root/majority-element/README.md index e69de29..69b0d60 100644 --- a/_includes/_root/majority-element/README.md +++ b/_includes/_root/majority-element/README.md @@ -0,0 +1,18 @@ +## [A Linear Time Majority Vote Algorithm](http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html) + +## Game: How to find 10 IPs which are flooding your server + +Imagine that there is an arena which can on only contains 10 people. +Every people is holding an IP. + +Now, throw the accessing IPs into the arena to hit the people with rule below: + + * a people is holding the same IP will get health `+1` + * if no people is holding the IP, the IP will hit a people randomly, that people's health `-1` + * people with health 0 will be kicked out of the arena and replace by new people hold current IP. + +at the end, people left in the arena with high health value are obviously the attackers. + + + + diff --git a/binary-search-tree-iterator/index.md b/binary-search-tree-iterator/index.md index ba5bedb..228521d 100644 --- a/binary-search-tree-iterator/index.md +++ b/binary-search-tree-iterator/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Search Tree Iterator -date: 2014-12-31 16:16:36 +0800 +date: 2015-01-03 03:26:48 +0800 leetcode_id: 173 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/factorial-trailing-zeroes/index.md b/factorial-trailing-zeroes/index.md index 8fac0c3..ea0c193 100644 --- a/factorial-trailing-zeroes/index.md +++ b/factorial-trailing-zeroes/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Factorial Trailing Zeroes -date: 2014-12-30 18:01:41 +0800 +date: 2015-01-03 03:36:44 +0800 leetcode_id: 172 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/majority-element/index.md b/majority-element/index.md index 1f0d4e9..eafead8 100644 --- a/majority-element/index.md +++ b/majority-element/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Majority Element -date: 2014-12-22 15:14:45 +0800 +date: 2015-01-03 03:53:03 +0800 leetcode_id: 169 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 1b06747233316f064b06be3d5ded9e9b039b1abc Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 7 Jan 2015 03:58:50 +0800 Subject: [PATCH 040/195] add wow game --- dungeon-game/README.md | 0 dungeon-game/Solution.java | 37 +++++++++++++++++++++++++++++++++++++ dungeon-game/index.md | 9 +++++++++ 3 files changed, 46 insertions(+) create mode 100644 dungeon-game/README.md create mode 100644 dungeon-game/Solution.java create mode 100644 dungeon-game/index.md diff --git a/dungeon-game/README.md b/dungeon-game/README.md new file mode 100644 index 0000000..e69de29 diff --git a/dungeon-game/Solution.java b/dungeon-game/Solution.java new file mode 100644 index 0000000..689cb88 --- /dev/null +++ b/dungeon-game/Solution.java @@ -0,0 +1,37 @@ +public class Solution { + + int minHealthReach(int hp, int room){ + hp -= room; + if(hp <= 0){ + return 1; + } + + return hp; + } + + public int calculateMinimumHP(int[][] dungeon) { + + final int mx = dungeon.length; + final int my = dungeon[0].length; + + dungeon[mx - 1][my - 1] = minHealthReach(1, dungeon[mx - 1][my - 1]); + + for(int i = mx - 2; i >= 0; i--){ + dungeon[i][my - 1] = minHealthReach(dungeon[i + 1][my - 1], dungeon[i][my - 1]); + } + + for(int j = my - 2; j >= 0; j--){ + dungeon[mx - 1][j] = minHealthReach(dungeon[mx - 1][j + 1], dungeon[mx - 1][j]); + } + + + for(int i = mx - 2; i >= 0; i--){ + for(int j = my - 2; j >= 0; j--){ + dungeon[i][j] = minHealthReach(Math.min(dungeon[i + 1][j], dungeon[i][j + 1]), dungeon[i][j]); + } + } + + return dungeon[0][0]; + + } +} diff --git a/dungeon-game/index.md b/dungeon-game/index.md new file mode 100644 index 0000000..fcb6856 --- /dev/null +++ b/dungeon-game/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Dungeon Game +date: 2015-01-07 03:57:19+08:00 +leetcode_id: 174 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 2eb70490b4fed4b301f2f030176f40b86cab58e4 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 7 Jan 2015 03:59:25 +0800 Subject: [PATCH 041/195] add wow game to gh-pages --- _includes/_root/dungeon-game/README.md | 0 _includes/_root/dungeon-game/Solution.java | 37 ++++++++++++++++++++++ dungeon-game/index.md | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/dungeon-game/README.md create mode 100644 _includes/_root/dungeon-game/Solution.java diff --git a/_includes/_root/dungeon-game/README.md b/_includes/_root/dungeon-game/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/dungeon-game/Solution.java b/_includes/_root/dungeon-game/Solution.java new file mode 100644 index 0000000..689cb88 --- /dev/null +++ b/_includes/_root/dungeon-game/Solution.java @@ -0,0 +1,37 @@ +public class Solution { + + int minHealthReach(int hp, int room){ + hp -= room; + if(hp <= 0){ + return 1; + } + + return hp; + } + + public int calculateMinimumHP(int[][] dungeon) { + + final int mx = dungeon.length; + final int my = dungeon[0].length; + + dungeon[mx - 1][my - 1] = minHealthReach(1, dungeon[mx - 1][my - 1]); + + for(int i = mx - 2; i >= 0; i--){ + dungeon[i][my - 1] = minHealthReach(dungeon[i + 1][my - 1], dungeon[i][my - 1]); + } + + for(int j = my - 2; j >= 0; j--){ + dungeon[mx - 1][j] = minHealthReach(dungeon[mx - 1][j + 1], dungeon[mx - 1][j]); + } + + + for(int i = mx - 2; i >= 0; i--){ + for(int j = my - 2; j >= 0; j--){ + dungeon[i][j] = minHealthReach(Math.min(dungeon[i + 1][j], dungeon[i][j + 1]), dungeon[i][j]); + } + } + + return dungeon[0][0]; + + } +} diff --git a/dungeon-game/index.md b/dungeon-game/index.md index fcb6856..59d949e 100644 --- a/dungeon-game/index.md +++ b/dungeon-game/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Dungeon Game -date: 2015-01-07 03:57:19+08:00 +date: 2015-01-07 03:58:50 +0800 leetcode_id: 174 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 940d3d4791e5f4831ee2e52ce068d58c5823e114 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 13 Jan 2015 12:21:26 +0800 Subject: [PATCH 042/195] add largest number --- largest-number/README.md | 0 largest-number/Solution.java | 12 ++++++++++++ largest-number/index.md | 9 +++++++++ 3 files changed, 21 insertions(+) create mode 100644 largest-number/README.md create mode 100644 largest-number/Solution.java create mode 100644 largest-number/index.md diff --git a/largest-number/README.md b/largest-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/largest-number/Solution.java b/largest-number/Solution.java new file mode 100644 index 0000000..869957e --- /dev/null +++ b/largest-number/Solution.java @@ -0,0 +1,12 @@ +public class Solution { + public String largestNumber(int[] num) { + + String[] ns = Arrays.stream(num).mapToObj(x -> "" + x).toArray(String[]::new); + + Arrays.sort(ns, (String x, String y) -> (y + x).compareTo(x + y)); + + if("0".equals(ns[0])) return "0"; + + return Arrays.stream(ns).reduce((x, y) -> x + y).get(); + } +} diff --git a/largest-number/index.md b/largest-number/index.md new file mode 100644 index 0000000..d208415 --- /dev/null +++ b/largest-number/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Largest Number +date: 2015-01-13 12:19:01+08:00 +leetcode_id: 179 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 3bdac6331f71677c3225b4612cb6d057ce918684 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 13 Jan 2015 12:24:34 +0800 Subject: [PATCH 043/195] love lambda largest number --- _includes/_root/largest-number/README.md | 0 _includes/_root/largest-number/Solution.java | 12 ++++++++++++ largest-number/index.md | 2 +- 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 _includes/_root/largest-number/README.md create mode 100644 _includes/_root/largest-number/Solution.java diff --git a/_includes/_root/largest-number/README.md b/_includes/_root/largest-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/_includes/_root/largest-number/Solution.java b/_includes/_root/largest-number/Solution.java new file mode 100644 index 0000000..869957e --- /dev/null +++ b/_includes/_root/largest-number/Solution.java @@ -0,0 +1,12 @@ +public class Solution { + public String largestNumber(int[] num) { + + String[] ns = Arrays.stream(num).mapToObj(x -> "" + x).toArray(String[]::new); + + Arrays.sort(ns, (String x, String y) -> (y + x).compareTo(x + y)); + + if("0".equals(ns[0])) return "0"; + + return Arrays.stream(ns).reduce((x, y) -> x + y).get(); + } +} diff --git a/largest-number/index.md b/largest-number/index.md index d208415..f3038cd 100644 --- a/largest-number/index.md +++ b/largest-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Largest Number -date: 2015-01-13 12:19:01+08:00 +date: 2015-01-13 12:21:26 +0800 leetcode_id: 179 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 78952a94c032d6f224ba7effe553934b493a01a1 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 13 Jan 2015 12:25:46 +0800 Subject: [PATCH 044/195] update todo --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index c850ee8..59db117 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,9 @@ Please [Donate leetcode](https://oj.leetcode.com/donate/) - -## Milestone - - * 151 AC _Jul 20 2014_ - * 151 Detailed solving thought _Aug 31 2014_ - - ## TODO * Evaluate the Time and Space complexity of each solution * Proof the code's correctness if needed * Find better solutions + * Rewrite code with Java8 lambda From 61d328fe0c742ce136793781b59548066c4af320 Mon Sep 17 00:00:00 2001 From: Prakash Natarajan Date: Fri, 16 Jan 2015 16:07:02 -0500 Subject: [PATCH 045/195] Update README.md --- sum-root-to-leaf-numbers/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sum-root-to-leaf-numbers/README.md b/sum-root-to-leaf-numbers/README.md index 82c2d56..73ef4c9 100644 --- a/sum-root-to-leaf-numbers/README.md +++ b/sum-root-to-leaf-numbers/README.md @@ -10,4 +10,4 @@ parent_val(node) = 0 [ node is ``` -I have written some versions using DFS and BSF, but they are not as clear as above. +I have written some versions using DFS and BFS, but they are not as clear as above. From 70340c1b26ce3c2b964f8c6aa12517e1f492ba0d Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 18 Jan 2015 03:14:54 +0800 Subject: [PATCH 046/195] update for overflow --- reverse-integer/Solution.java | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/reverse-integer/Solution.java b/reverse-integer/Solution.java index 7d0fb3c..39688e3 100644 --- a/reverse-integer/Solution.java +++ b/reverse-integer/Solution.java @@ -1,23 +1,24 @@ public class Solution { public int reverse(int x) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(x == 0) return 0; - if(x < 0) return -reverse(-x); - int len = (int)Math.log10(x) + 1; - int[] y = new int[len]; + if(x == Integer.MIN_VALUE) return 0; + if(x < 0) return -reverse(-x); - int i = 0; - while(i < len){ - y[i] = x % 10; + int y = 0; + + do { + + // y * 10 + x % 10 > Integer.MAX_VALUE + if(y > (Integer.MAX_VALUE - x % 10) / 10){ + return 0; + } + + y = y * 10 + x % 10; + x /= 10; - i++; - } - - int s = 0; - for(i = len - 1; i >=0 ; i--) - s += y[i] * Math.pow(10, len - 1 - i); - - return s; + + } while(x > 0); + + return y; } -} \ No newline at end of file +} From 7f6bfaecc455b04560d9bbdaa638c7ad7937e00d Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 18 Jan 2015 03:28:07 +0800 Subject: [PATCH 047/195] move to list --- .../Solution.java | 45 +++++++++---------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/letter-combinations-of-a-phone-number/Solution.java b/letter-combinations-of-a-phone-number/Solution.java index b5c047b..85e7a81 100644 --- a/letter-combinations-of-a-phone-number/Solution.java +++ b/letter-combinations-of-a-phone-number/Solution.java @@ -1,21 +1,21 @@ public class Solution { static final char[][] CHAR_MAP = { - null, // 0 - null, // 1 - new char[] { 'a', 'b', 'c'}, //2 - new char[] { 'd', 'e', 'f'}, //3 - new char[] { 'g', 'h', 'i'}, //4 - new char[] { 'j', 'k', 'l'}, //5 - new char[] { 'm', 'n', 'o'}, //6 - new char[] { 'p', 'q', 'r', 's'}, //7 - new char[] { 't', 'u', 'v'}, //8 - new char[] { 'w', 'x', 'y', 'z'}, //9 - }; - + {}, // 0 + {}, // 1 + { 'a', 'b', 'c'}, //2 + { 'd', 'e', 'f'}, //3 + { 'g', 'h', 'i'}, //4 + { 'j', 'k', 'l'}, //5 + { 'm', 'n', 'o'}, //6 + { 'p', 'q', 'r', 's'}, //7 + { 't', 'u', 'v'}, //8 + { 'w', 'x', 'y', 'z'}, //9 + }; + ArrayList rt; char[] stack; - + void find(char[] digits, int p){ if(p == digits.length){ @@ -24,22 +24,19 @@ void find(char[] digits, int p){ int num = (int) (digits[p] - '0'); - if(CHAR_MAP[num] != null) - for(char pc : CHAR_MAP[num]){ - stack[p] = pc; - find(digits, p + 1); - } + for(char pc : CHAR_MAP[num]){ + stack[p] = pc; + find(digits, p + 1); + } } - - } + } - public ArrayList letterCombinations(String digits) { + public List letterCombinations(String digits) { - rt = new ArrayList(); + rt = new ArrayList<>(); stack = new char[digits.length()]; find(digits.toCharArray(), 0); - return rt; } -} \ No newline at end of file +} From a5d7ba730cfcd0a71079a9dc00d7741a5417382c Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 14 Jan 2015 11:09:14 +0800 Subject: [PATCH 048/195] change to collector --- largest-number/Solution.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/largest-number/Solution.java b/largest-number/Solution.java index 869957e..c7f2116 100644 --- a/largest-number/Solution.java +++ b/largest-number/Solution.java @@ -7,6 +7,6 @@ public String largestNumber(int[] num) { if("0".equals(ns[0])) return "0"; - return Arrays.stream(ns).reduce((x, y) -> x + y).get(); + return Arrays.stream(ns).collect(Collectors.joining()); } } From 4466efb04302c7e6fabaabf52f7ba8b7182cb5d5 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 18 Jan 2015 15:03:35 +0800 Subject: [PATCH 049/195] commit changes to gh-pages --- _includes/_root/largest-number/Solution.java | 2 +- .../Solution.java | 45 +++++++++---------- _includes/_root/reverse-integer/Solution.java | 35 ++++++++------- .../_root/sum-root-to-leaf-numbers/README.md | 2 +- largest-number/index.md | 2 +- .../index.md | 2 +- reverse-integer/index.md | 2 +- sum-root-to-leaf-numbers/index.md | 2 +- 8 files changed, 45 insertions(+), 47 deletions(-) diff --git a/_includes/_root/largest-number/Solution.java b/_includes/_root/largest-number/Solution.java index 869957e..c7f2116 100644 --- a/_includes/_root/largest-number/Solution.java +++ b/_includes/_root/largest-number/Solution.java @@ -7,6 +7,6 @@ public String largestNumber(int[] num) { if("0".equals(ns[0])) return "0"; - return Arrays.stream(ns).reduce((x, y) -> x + y).get(); + return Arrays.stream(ns).collect(Collectors.joining()); } } diff --git a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java b/_includes/_root/letter-combinations-of-a-phone-number/Solution.java index b5c047b..85e7a81 100644 --- a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java +++ b/_includes/_root/letter-combinations-of-a-phone-number/Solution.java @@ -1,21 +1,21 @@ public class Solution { static final char[][] CHAR_MAP = { - null, // 0 - null, // 1 - new char[] { 'a', 'b', 'c'}, //2 - new char[] { 'd', 'e', 'f'}, //3 - new char[] { 'g', 'h', 'i'}, //4 - new char[] { 'j', 'k', 'l'}, //5 - new char[] { 'm', 'n', 'o'}, //6 - new char[] { 'p', 'q', 'r', 's'}, //7 - new char[] { 't', 'u', 'v'}, //8 - new char[] { 'w', 'x', 'y', 'z'}, //9 - }; - + {}, // 0 + {}, // 1 + { 'a', 'b', 'c'}, //2 + { 'd', 'e', 'f'}, //3 + { 'g', 'h', 'i'}, //4 + { 'j', 'k', 'l'}, //5 + { 'm', 'n', 'o'}, //6 + { 'p', 'q', 'r', 's'}, //7 + { 't', 'u', 'v'}, //8 + { 'w', 'x', 'y', 'z'}, //9 + }; + ArrayList rt; char[] stack; - + void find(char[] digits, int p){ if(p == digits.length){ @@ -24,22 +24,19 @@ void find(char[] digits, int p){ int num = (int) (digits[p] - '0'); - if(CHAR_MAP[num] != null) - for(char pc : CHAR_MAP[num]){ - stack[p] = pc; - find(digits, p + 1); - } + for(char pc : CHAR_MAP[num]){ + stack[p] = pc; + find(digits, p + 1); + } } - - } + } - public ArrayList letterCombinations(String digits) { + public List letterCombinations(String digits) { - rt = new ArrayList(); + rt = new ArrayList<>(); stack = new char[digits.length()]; find(digits.toCharArray(), 0); - return rt; } -} \ No newline at end of file +} diff --git a/_includes/_root/reverse-integer/Solution.java b/_includes/_root/reverse-integer/Solution.java index 7d0fb3c..39688e3 100644 --- a/_includes/_root/reverse-integer/Solution.java +++ b/_includes/_root/reverse-integer/Solution.java @@ -1,23 +1,24 @@ public class Solution { public int reverse(int x) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(x == 0) return 0; - if(x < 0) return -reverse(-x); - int len = (int)Math.log10(x) + 1; - int[] y = new int[len]; + if(x == Integer.MIN_VALUE) return 0; + if(x < 0) return -reverse(-x); - int i = 0; - while(i < len){ - y[i] = x % 10; + int y = 0; + + do { + + // y * 10 + x % 10 > Integer.MAX_VALUE + if(y > (Integer.MAX_VALUE - x % 10) / 10){ + return 0; + } + + y = y * 10 + x % 10; + x /= 10; - i++; - } - - int s = 0; - for(i = len - 1; i >=0 ; i--) - s += y[i] * Math.pow(10, len - 1 - i); - - return s; + + } while(x > 0); + + return y; } -} \ No newline at end of file +} diff --git a/_includes/_root/sum-root-to-leaf-numbers/README.md b/_includes/_root/sum-root-to-leaf-numbers/README.md index 82c2d56..73ef4c9 100644 --- a/_includes/_root/sum-root-to-leaf-numbers/README.md +++ b/_includes/_root/sum-root-to-leaf-numbers/README.md @@ -10,4 +10,4 @@ parent_val(node) = 0 [ node is ``` -I have written some versions using DFS and BSF, but they are not as clear as above. +I have written some versions using DFS and BFS, but they are not as clear as above. diff --git a/largest-number/index.md b/largest-number/index.md index f3038cd..f771171 100644 --- a/largest-number/index.md +++ b/largest-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Largest Number -date: 2015-01-13 12:21:26 +0800 +date: 2015-01-14 11:09:14 +0800 leetcode_id: 179 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/letter-combinations-of-a-phone-number/index.md b/letter-combinations-of-a-phone-number/index.md index 63f2cf0..8c9632e 100644 --- a/letter-combinations-of-a-phone-number/index.md +++ b/letter-combinations-of-a-phone-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Letter Combinations of a Phone Number -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-18 03:28:07 +0800 leetcode_id: 17 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-integer/index.md b/reverse-integer/index.md index 4cd0a35..813d566 100644 --- a/reverse-integer/index.md +++ b/reverse-integer/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Integer -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-18 03:14:54 +0800 leetcode_id: 7 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sum-root-to-leaf-numbers/index.md b/sum-root-to-leaf-numbers/index.md index c9923d3..ebd2a0f 100644 --- a/sum-root-to-leaf-numbers/index.md +++ b/sum-root-to-leaf-numbers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sum Root to Leaf Numbers -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-16 16:07:02 -0500 leetcode_id: 129 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 28aced42eaedca863bb429fa239d64d9464d14a7 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 18 Jan 2015 23:39:27 +0800 Subject: [PATCH 050/195] java8 style --- anagrams/Solution.java | 46 ++++++++++++++---------------------------- 1 file changed, 15 insertions(+), 31 deletions(-) diff --git a/anagrams/Solution.java b/anagrams/Solution.java index 4bea62c..7301fb1 100644 --- a/anagrams/Solution.java +++ b/anagrams/Solution.java @@ -1,33 +1,17 @@ public class Solution { - public ArrayList anagrams(String[] strs) { - ArrayList found = new ArrayList(); - - HashMap> box = new HashMap>(); - - for(String str : strs){ - char[] cstr = str.toCharArray(); - Arrays.sort(cstr); - - String key = new String(cstr); - - ArrayList c = box.get(key); - if(c == null){ - box.put(key , new ArrayList()); - } - - c = box.get(key); - c.add(str); - - } - - for(ArrayList s : box.values()){ - - if(s.size() > 1){ - found.addAll(s); - } - - } - - return found; + public List anagrams(String[] strs) { + return Arrays.stream(strs) + .collect(Collectors.groupingBy( + k -> { + char[] w = k.toCharArray(); + Arrays.sort(w); + return new String(w); + } + )) + .values() + .stream() + .filter(v -> v.size() > 1) + .flatMap(v -> v.stream()) + .collect(Collectors.toList()); } -} \ No newline at end of file +} From 89043f98576ef281dab54a87ad5a285edfce5fe7 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 18 Jan 2015 23:48:07 +0800 Subject: [PATCH 051/195] add what the fuck method --- sqrtx/README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/sqrtx/README.md b/sqrtx/README.md index 3289b7a..f4ad433 100644 --- a/sqrtx/README.md +++ b/sqrtx/README.md @@ -66,4 +66,24 @@ To avoid this, change any `+` and `*` to `-` and `/` * `(m + 1)^2 == x` -> `x / (m + 1) == (m + 1)` +## [0x5f3759df](http://en.wikipedia.org/wiki/Fast_inverse_square_root) + +``` +float Q_rsqrt( float number ) +{ + long i; + float x2, y; + const float threehalfs = 1.5F; + + x2 = number * 0.5F; + y = number; + i = * ( long * ) &y; // evil floating point bit level hacking + i = 0x5f3759df - ( i >> 1 ); // what the fuck? + y = * ( float * ) &i; + y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration +// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed + + return y; +} +``` From 50949626996595e6877f3c8aaa4a5cbac8279383 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:08:01 +0800 Subject: [PATCH 052/195] simplify --- reverse-words-in-a-string/Solution.java | 36 ++++--------------------- 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/reverse-words-in-a-string/Solution.java b/reverse-words-in-a-string/Solution.java index b760659..b87d180 100644 --- a/reverse-words-in-a-string/Solution.java +++ b/reverse-words-in-a-string/Solution.java @@ -1,35 +1,9 @@ public class Solution { public String reverseWords(String s) { - if(s == null) return null; - - - ArrayList words = new ArrayList(); - - StringBuilder buff = new StringBuilder(); - - for(char c : (s + " ").toCharArray()){ - if (c != ' '){ - buff.append(c); - }else{ - String w = buff.toString(); - if(!"".equals(w)){ - words.add(w); - buff = new StringBuilder(); - } - } - } - - if(words.size() == 0) return ""; - - buff = new StringBuilder(); - for(int i = words.size() - 1; i >0 ; i--){ - buff.append(words.get(i)); - buff.append(' '); - } - - buff.append(words.get(0)); - - return buff.toString(); + List words = Arrays.asList(s.trim().split(" +")); + + Collections.reverse(words); + return String.join(" ", words); } -} \ No newline at end of file +} From a2df1209cc0d85bdc827cb7a22b9dbafd4a2ccc0 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:17:27 +0800 Subject: [PATCH 053/195] java8-ic --- largest-number/Solution.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/largest-number/Solution.java b/largest-number/Solution.java index c7f2116..5e303a7 100644 --- a/largest-number/Solution.java +++ b/largest-number/Solution.java @@ -1,12 +1,12 @@ public class Solution { - public String largestNumber(int[] num) { + public String largestNumber(int[] num) { + String[] ns = Arrays.stream(num) + .mapToObj(Integer::toString) + .sorted((x, y) -> (y + x).compareTo(x + y)) + .toArray(String[]::new); - String[] ns = Arrays.stream(num).mapToObj(x -> "" + x).toArray(String[]::new); + if ("0".equals(ns[0])) return "0"; - Arrays.sort(ns, (String x, String y) -> (y + x).compareTo(x + y)); - - if("0".equals(ns[0])) return "0"; - - return Arrays.stream(ns).collect(Collectors.joining()); - } + return String.join("", ns); + } } From 962fea1d9fec8bc7c900944a43b9faf1c75d2c35 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:40:37 +0800 Subject: [PATCH 054/195] smart include with submod --- .gitmodules | 4 + _includes/_root | 1 + _includes/_root/3sum-closest/README.md | 3 - _includes/_root/3sum-closest/Solution.java | 36 --- _includes/_root/3sum/README.md | 32 --- _includes/_root/3sum/Solution.java | 38 --- _includes/_root/4sum/README.md | 8 - _includes/_root/4sum/Solution.java | 83 ------ _includes/_root/add-binary/README.md | 4 - _includes/_root/add-binary/Solution.java | 47 ---- _includes/_root/add-two-numbers/README.md | 3 - _includes/_root/add-two-numbers/Solution.java | 50 ---- _includes/_root/anagrams/README.md | 7 - _includes/_root/anagrams/Solution.java | 33 --- .../_root/balanced-binary-tree/README.md | 9 - .../_root/balanced-binary-tree/Solution.java | 30 --- .../README.md | 7 - .../Solution.java | 24 -- .../README.md | 39 --- .../Solution.java | 32 --- .../best-time-to-buy-and-sell-stock/README.md | 20 -- .../Solution.java | 17 -- .../binary-search-tree-iterator/README.md | 43 --- .../binary-search-tree-iterator/Solution.java | 91 ------- .../binary-tree-inorder-traversal/README.md | 100 ------- .../Solution.java | 68 ----- .../README.md | 3 - .../Solution.java | 46 ---- .../README.md | 77 ------ .../Solution.java | 48 ---- .../binary-tree-maximum-path-sum/README.md | 83 ------ .../Solution.java | 36 --- .../binary-tree-postorder-traversal/README.md | 5 - .../Solution.java | 69 ----- .../binary-tree-preorder-traversal/README.md | 5 - .../Solution.java | 68 ----- .../_root/binary-tree-upside-down/README.md | 37 --- .../binary-tree-upside-down/Solution.java | 48 ---- .../README.md | 6 - .../Solution.java | 58 ---- _includes/_root/candy/README.md | 12 - _includes/_root/candy/Solution.java | 26 -- _includes/_root/climbing-stairs/README.md | 19 -- _includes/_root/climbing-stairs/Solution.java | 19 -- _includes/_root/clone-graph/README.md | 6 - _includes/_root/clone-graph/Solution.java | 54 ---- _includes/_root/combination-sum-ii/README.md | 3 - .../_root/combination-sum-ii/Solution.java | 63 ----- _includes/_root/combination-sum/README.md | 12 - _includes/_root/combination-sum/Solution.java | 56 ---- _includes/_root/combinations/README.md | 9 - _includes/_root/combinations/Solution.java | 39 --- .../_root/compare-version-numbers/README.md | 0 .../compare-version-numbers/Solution.java | 48 ---- .../README.md | 14 - .../Solution.java | 40 --- .../README.md | 27 -- .../Solution.java | 44 ---- .../_root/container-with-most-water/README.md | 122 --------- .../container-with-most-water/Solution.java | 32 --- .../README.md | 18 -- .../Solution.java | 32 --- .../README.md | 5 - .../Solution.java | 53 ---- .../copy-list-with-random-pointer/README.md | 3 - .../Solution.java | 38 --- _includes/_root/count-and-say/README.md | 8 - _includes/_root/count-and-say/Solution.java | 45 ---- _includes/_root/decode-ways/README.md | 13 - _includes/_root/decode-ways/Solution.java | 39 --- .../_root/distinct-subsequences/README.md | 194 -------------- .../_root/distinct-subsequences/Solution.java | 50 ---- _includes/_root/divide-two-integers/README.md | 36 --- .../_root/divide-two-integers/Solution.java | 43 --- _includes/_root/dungeon-game/README.md | 0 _includes/_root/dungeon-game/Solution.java | 37 --- _includes/_root/edit-distance/README.md | 164 ------------ _includes/_root/edit-distance/Solution.java | 39 --- .../README.md | 6 - .../Solution.java | 35 --- .../_root/excel-sheet-column-number/README.md | 0 .../excel-sheet-column-number/Solution.java | 18 -- .../_root/excel-sheet-column-title/README.md | 0 .../excel-sheet-column-title/Solution.java | 13 - .../_root/factorial-trailing-zeroes/README.md | 11 - .../factorial-trailing-zeroes/Solution.java | 33 --- .../README.md | 16 -- .../Solution.java | 30 --- .../README.md | 55 ---- .../Solution.java | 25 -- _includes/_root/find-peak-element/README.md | 11 - .../_root/find-peak-element/Solution.java | 18 -- .../_root/first-missing-positive/README.md | 133 ---------- .../first-missing-positive/Solution.java | 40 --- .../README.md | 3 - .../Solution.java | 39 --- .../fraction-to-recurring-decimal/README.md | 0 .../Solution.java | 55 ---- _includes/_root/gas-station/README.md | 14 - _includes/_root/gas-station/Solution.java | 27 -- .../_root/generate-parentheses/README.md | 22 -- .../_root/generate-parentheses/Solution.java | 28 -- _includes/_root/gray-code/README.md | 8 - _includes/_root/gray-code/Solution.java | 15 -- _includes/_root/implement-strstr/README.md | 241 ----------------- .../_root/implement-strstr/Solution.java | 45 ---- _includes/_root/insert-interval/README.md | 8 - _includes/_root/insert-interval/Solution.java | 45 ---- _includes/_root/insertion-sort-list/README.md | 7 - .../_root/insertion-sort-list/Solution.java | 59 ----- _includes/_root/integer-to-roman/README.md | 4 - .../_root/integer-to-roman/Solution.java | 61 ----- _includes/_root/interleaving-string/README.md | 89 ------- .../_root/interleaving-string/Solution.java | 45 ---- .../README.md | 22 -- .../Solution.java | 74 ------ _includes/_root/jump-game-ii/README.md | 10 - _includes/_root/jump-game-ii/Solution.java | 21 -- _includes/_root/jump-game/README.md | 67 ----- _includes/_root/jump-game/Solution.java | 26 -- _includes/_root/largest-number/README.md | 0 _includes/_root/largest-number/Solution.java | 12 - .../largest-rectangle-in-histogram/README.md | 248 ------------------ .../Solution.java | 52 ---- _includes/_root/length-of-last-word/README.md | 4 - .../_root/length-of-last-word/Solution.java | 21 -- .../README.md | 7 - .../Solution.java | 42 --- .../_root/linked-list-cycle-ii/README.md | 25 -- .../_root/linked-list-cycle-ii/Solution.java | 70 ----- _includes/_root/linked-list-cycle/README.md | 26 -- .../_root/linked-list-cycle/Solution.java | 37 --- .../_root/longest-common-prefix/README.md | 5 - .../_root/longest-common-prefix/Solution.java | 32 --- .../longest-consecutive-sequence/README.md | 117 --------- .../Solution.java | 38 --- .../longest-palindromic-substring/README.md | 67 ----- .../Solution.java | 40 --- .../README.md | 36 --- .../Solution.java | 68 ----- .../README.md | 21 -- .../Solution.java | 28 -- .../_root/longest-valid-parentheses/README.md | 74 ------ .../longest-valid-parentheses/Solution.java | 33 --- _includes/_root/lru-cache/README.md | 105 -------- _includes/_root/lru-cache/Solution.java | 150 ----------- _includes/_root/majority-element/README.md | 18 -- .../_root/majority-element/Solution.java | 18 -- .../_root/max-points-on-a-line/README.md | 74 ------ .../_root/max-points-on-a-line/Solution.java | 78 ------ _includes/_root/maximal-rectangle/README.md | 70 ----- .../_root/maximal-rectangle/Solution.java | 116 -------- .../maximum-depth-of-binary-tree/README.md | 6 - .../Solution.java | 17 -- _includes/_root/maximum-gap/README.md | 32 --- _includes/_root/maximum-gap/Solution.java | 52 ---- .../_root/maximum-product-subarray/README.md | 12 - .../maximum-product-subarray/Solution.java | 28 -- _includes/_root/maximum-subarray/README.md | 24 -- .../_root/maximum-subarray/Solution.java | 20 -- .../median-of-two-sorted-arrays/README.md | 159 ----------- .../median-of-two-sorted-arrays/Solution.java | 80 ------ _includes/_root/merge-intervals/README.md | 64 ----- _includes/_root/merge-intervals/Solution.java | 39 --- .../_root/merge-k-sorted-lists/README.md | 34 --- .../_root/merge-k-sorted-lists/Solution.java | 47 ---- _includes/_root/merge-sorted-array/README.md | 23 -- .../_root/merge-sorted-array/Solution.java | 33 --- .../_root/merge-two-sorted-lists/README.md | 3 - .../merge-two-sorted-lists/Solution.java | 38 --- _includes/_root/min-stack/README.md | 23 -- _includes/_root/min-stack/Solution.java | 66 ----- .../minimum-depth-of-binary-tree/README.md | 12 - .../Solution.java | 22 -- _includes/_root/minimum-path-sum/README.md | 65 ----- .../_root/minimum-path-sum/Solution.java | 28 -- .../_root/minimum-window-substring/README.md | 79 ------ .../minimum-window-substring/Solution.java | 64 ----- _includes/_root/missing-ranges/README.md | 63 ----- _includes/_root/missing-ranges/Solution.java | 52 ---- _includes/_root/multiply-strings/README.md | 10 - .../_root/multiply-strings/Solution.java | 41 --- _includes/_root/n-queens-ii/README.md | 3 - _includes/_root/n-queens-ii/Solution.java | 58 ---- _includes/_root/n-queens/README.md | 92 ------- _includes/_root/n-queens/Solution.java | 67 ----- _includes/_root/next-permutation/README.md | 14 - .../_root/next-permutation/Solution.java | 39 --- _includes/_root/one-edit-distance/README.md | 26 -- .../_root/one-edit-distance/Solution.java | 37 --- _includes/_root/palindrome-number/README.md | 10 - .../_root/palindrome-number/Solution.java | 26 -- .../palindrome-partitioning-ii/README.md | 16 -- .../palindrome-partitioning-ii/Solution.java | 49 ---- .../_root/palindrome-partitioning/README.md | 9 - .../palindrome-partitioning/Solution.java | 45 ---- _includes/_root/partition-list/README.md | 8 - _includes/_root/partition-list/Solution.java | 43 --- _includes/_root/pascals-triangle-ii/README.md | 3 - .../_root/pascals-triangle-ii/Solution.java | 15 -- _includes/_root/pascals-triangle/README.md | 22 -- .../_root/pascals-triangle/Solution.java | 28 -- _includes/_root/path-sum-ii/README.md | 16 -- _includes/_root/path-sum-ii/Solution.java | 44 ---- _includes/_root/path-sum/README.md | 5 - _includes/_root/path-sum/Solution.java | 27 -- .../_root/permutation-sequence/README.md | 132 ---------- .../_root/permutation-sequence/Solution.java | 40 --- _includes/_root/permutations-ii/README.md | 23 -- _includes/_root/permutations-ii/Solution.java | 61 ----- _includes/_root/permutations/README.md | 13 - _includes/_root/permutations/Solution.java | 35 --- _includes/_root/plus-one/README.md | 21 -- _includes/_root/plus-one/Solution.java | 17 -- .../README.md | 30 --- .../Solution.java | 47 ---- .../README.md | 38 --- .../Solution.java | 26 -- _includes/_root/powx-n/README.md | 9 - _includes/_root/powx-n/Solution.java | 17 -- .../README.md | 23 -- .../Solution.java | 37 --- .../read-n-characters-given-read4/README.md | 14 - .../Solution.java | 31 --- .../recover-binary-search-tree/README.md | 5 - .../recover-binary-search-tree/Solution.java | 53 ---- .../regular-expression-matching/README.md | 21 -- .../regular-expression-matching/Solution.java | 232 ---------------- .../README.md | 10 - .../Solution.java | 25 -- .../README.md | 26 -- .../Solution.java | 19 -- .../README.md | 9 - .../Solution.java | 37 --- .../README.md | 4 - .../Solution.java | 36 --- _includes/_root/remove-element/README.md | 4 - _includes/_root/remove-element/Solution.java | 16 -- .../README.md | 7 - .../Solution.java | 36 --- _includes/_root/reorder-list/README.md | 28 -- _includes/_root/reorder-list/Solution.java | 75 ------ .../_root/restore-ip-addresses/README.md | 14 - .../_root/restore-ip-addresses/Solution.java | 46 ---- _includes/_root/reverse-integer/README.md | 5 - _includes/_root/reverse-integer/Solution.java | 24 -- .../_root/reverse-linked-list-ii/README.md | 8 - .../reverse-linked-list-ii/Solution.java | 64 ----- .../_root/reverse-nodes-in-k-group/README.md | 5 - .../reverse-nodes-in-k-group/Solution.java | 57 ---- .../_root/reverse-words-in-a-string/README.md | 19 -- .../reverse-words-in-a-string/Solution.java | 35 --- _includes/_root/roman-to-integer/README.md | 20 -- .../_root/roman-to-integer/Solution.java | 55 ---- _includes/_root/rotate-image/README.md | 62 ----- _includes/_root/rotate-image/Solution.java | 38 --- _includes/_root/rotate-list/README.md | 6 - _includes/_root/rotate-list/Solution.java | 41 --- _includes/_root/same-tree/README.md | 9 - _includes/_root/same-tree/Solution.java | 21 -- _includes/_root/scramble-string/README.md | 127 --------- _includes/_root/scramble-string/Solution.java | 173 ------------ _includes/_root/search-a-2d-matrix/README.md | 39 --- .../_root/search-a-2d-matrix/Solution.java | 30 --- _includes/_root/search-for-a-range/README.md | 19 -- .../_root/search-for-a-range/Solution.java | 29 -- .../README.md | 73 ------ .../Solution.java | 60 ----- .../search-in-rotated-sorted-array/README.md | 139 ---------- .../Solution.java | 43 --- .../_root/search-insert-position/README.md | 20 -- .../search-insert-position/Solution.java | 9 - _includes/_root/set-matrix-zeroes/README.md | 13 - .../_root/set-matrix-zeroes/Solution.java | 65 ----- _includes/_root/simplify-path/README.md | 48 ---- _includes/_root/simplify-path/Solution.java | 44 ---- _includes/_root/single-number-ii/README.md | 27 -- .../_root/single-number-ii/Solution.java | 32 --- _includes/_root/single-number/README.md | 28 -- _includes/_root/single-number/Solution.java | 13 - _includes/_root/sort-colors/README.md | 101 ------- _includes/_root/sort-colors/Solution.java | 36 --- _includes/_root/sort-list/README.md | 14 - _includes/_root/sort-list/Solution.java | 60 ----- _includes/_root/spiral-matrix-ii/README.md | 5 - .../_root/spiral-matrix-ii/Solution.java | 43 --- _includes/_root/spiral-matrix/README.md | 3 - _includes/_root/spiral-matrix/Solution.java | 41 --- _includes/_root/sqrtx/README.md | 69 ----- _includes/_root/sqrtx/Solution.java | 41 --- .../_root/string-to-integer-atoi/README.md | 11 - .../string-to-integer-atoi/Solution.java | 64 ----- _includes/_root/subsets-ii/README.md | 3 - _includes/_root/subsets-ii/Solution.java | 49 ---- _includes/_root/subsets/README.md | 71 ----- _includes/_root/subsets/Solution.java | 34 --- .../README.md | 38 --- .../Solution.java | 61 ----- _includes/_root/sudoku-solver/README.md | 16 -- _includes/_root/sudoku-solver/Solution.java | 117 --------- .../_root/sum-root-to-leaf-numbers/README.md | 13 - .../sum-root-to-leaf-numbers/Solution.java | 27 -- _includes/_root/surrounded-regions/README.md | 19 -- .../_root/surrounded-regions/Solution.java | 101 ------- _includes/_root/swap-nodes-in-pairs/README.md | 9 - .../_root/swap-nodes-in-pairs/Solution.java | 28 -- _includes/_root/symmetric-tree/README.md | 5 - _includes/_root/symmetric-tree/Solution.java | 75 ------ _includes/_root/text-justification/README.md | 6 - .../_root/text-justification/Solution.java | 64 ----- _includes/_root/trapping-rain-water/README.md | 230 ---------------- .../_root/trapping-rain-water/Solution.java | 72 ----- _includes/_root/triangle/README.md | 23 -- _includes/_root/triangle/Solution.java | 27 -- .../README.md | 0 .../Solution.java | 20 -- .../README.md | 0 .../Solution.java | 32 --- _includes/_root/two-sum/README.md | 4 - _includes/_root/two-sum/Solution.java | 21 -- .../unique-binary-search-trees-ii/README.md | 5 - .../Solution.java | 42 --- .../unique-binary-search-trees/README.md | 42 --- .../unique-binary-search-trees/Solution.java | 15 -- _includes/_root/unique-paths-ii/README.md | 36 --- _includes/_root/unique-paths-ii/Solution.java | 40 --- _includes/_root/unique-paths/README.md | 91 ------- _includes/_root/unique-paths/Solution.java | 26 -- _includes/_root/valid-number/README.md | 8 - _includes/_root/valid-number/Solution.java | 44 ---- _includes/_root/valid-palindrome/README.md | 6 - .../_root/valid-palindrome/Solution.java | 29 -- _includes/_root/valid-parentheses/README.md | 24 -- .../_root/valid-parentheses/Solution.java | 29 -- _includes/_root/valid-sudoku/README.md | 19 -- _includes/_root/valid-sudoku/Solution.java | 55 ---- .../validate-binary-search-tree/README.md | 5 - .../validate-binary-search-tree/Solution.java | 38 --- _includes/_root/wildcard-matching/README.md | 62 ----- .../_root/wildcard-matching/Solution.java | 58 ---- _includes/_root/word-break-ii/README.md | 39 --- _includes/_root/word-break-ii/Solution.java | 67 ----- _includes/_root/word-break/README.md | 41 --- _includes/_root/word-break/Solution.java | 23 -- _includes/_root/word-ladder-ii/README.md | 35 --- _includes/_root/word-ladder-ii/Solution.java | 136 ---------- _includes/_root/word-ladder/README.md | 17 -- _includes/_root/word-ladder/Solution.java | 59 ----- _includes/_root/word-search/README.md | 11 - _includes/_root/word-search/Solution.java | 85 ------ _includes/_root/zigzag-conversion/README.md | 15 -- .../_root/zigzag-conversion/Solution.java | 56 ---- _layouts/solution.html | 2 +- 353 files changed, 6 insertions(+), 13753 deletions(-) create mode 100644 .gitmodules create mode 160000 _includes/_root delete mode 100644 _includes/_root/3sum-closest/README.md delete mode 100644 _includes/_root/3sum-closest/Solution.java delete mode 100644 _includes/_root/3sum/README.md delete mode 100644 _includes/_root/3sum/Solution.java delete mode 100644 _includes/_root/4sum/README.md delete mode 100644 _includes/_root/4sum/Solution.java delete mode 100644 _includes/_root/add-binary/README.md delete mode 100644 _includes/_root/add-binary/Solution.java delete mode 100644 _includes/_root/add-two-numbers/README.md delete mode 100644 _includes/_root/add-two-numbers/Solution.java delete mode 100644 _includes/_root/anagrams/README.md delete mode 100644 _includes/_root/anagrams/Solution.java delete mode 100644 _includes/_root/balanced-binary-tree/README.md delete mode 100644 _includes/_root/balanced-binary-tree/Solution.java delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock-ii/README.md delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock-iii/README.md delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock/README.md delete mode 100644 _includes/_root/best-time-to-buy-and-sell-stock/Solution.java delete mode 100644 _includes/_root/binary-search-tree-iterator/README.md delete mode 100644 _includes/_root/binary-search-tree-iterator/Solution.java delete mode 100644 _includes/_root/binary-tree-inorder-traversal/README.md delete mode 100644 _includes/_root/binary-tree-inorder-traversal/Solution.java delete mode 100644 _includes/_root/binary-tree-level-order-traversal-ii/README.md delete mode 100644 _includes/_root/binary-tree-level-order-traversal-ii/Solution.java delete mode 100644 _includes/_root/binary-tree-level-order-traversal/README.md delete mode 100644 _includes/_root/binary-tree-level-order-traversal/Solution.java delete mode 100644 _includes/_root/binary-tree-maximum-path-sum/README.md delete mode 100644 _includes/_root/binary-tree-maximum-path-sum/Solution.java delete mode 100644 _includes/_root/binary-tree-postorder-traversal/README.md delete mode 100644 _includes/_root/binary-tree-postorder-traversal/Solution.java delete mode 100644 _includes/_root/binary-tree-preorder-traversal/README.md delete mode 100644 _includes/_root/binary-tree-preorder-traversal/Solution.java delete mode 100644 _includes/_root/binary-tree-upside-down/README.md delete mode 100644 _includes/_root/binary-tree-upside-down/Solution.java delete mode 100644 _includes/_root/binary-tree-zigzag-level-order-traversal/README.md delete mode 100644 _includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java delete mode 100644 _includes/_root/candy/README.md delete mode 100644 _includes/_root/candy/Solution.java delete mode 100644 _includes/_root/climbing-stairs/README.md delete mode 100644 _includes/_root/climbing-stairs/Solution.java delete mode 100644 _includes/_root/clone-graph/README.md delete mode 100644 _includes/_root/clone-graph/Solution.java delete mode 100644 _includes/_root/combination-sum-ii/README.md delete mode 100644 _includes/_root/combination-sum-ii/Solution.java delete mode 100644 _includes/_root/combination-sum/README.md delete mode 100644 _includes/_root/combination-sum/Solution.java delete mode 100644 _includes/_root/combinations/README.md delete mode 100644 _includes/_root/combinations/Solution.java delete mode 100644 _includes/_root/compare-version-numbers/README.md delete mode 100644 _includes/_root/compare-version-numbers/Solution.java delete mode 100644 _includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/README.md delete mode 100644 _includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java delete mode 100644 _includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/README.md delete mode 100644 _includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java delete mode 100644 _includes/_root/container-with-most-water/README.md delete mode 100644 _includes/_root/container-with-most-water/Solution.java delete mode 100644 _includes/_root/convert-sorted-array-to-binary-search-tree/README.md delete mode 100644 _includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java delete mode 100644 _includes/_root/convert-sorted-list-to-binary-search-tree/README.md delete mode 100644 _includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java delete mode 100644 _includes/_root/copy-list-with-random-pointer/README.md delete mode 100644 _includes/_root/copy-list-with-random-pointer/Solution.java delete mode 100644 _includes/_root/count-and-say/README.md delete mode 100644 _includes/_root/count-and-say/Solution.java delete mode 100644 _includes/_root/decode-ways/README.md delete mode 100644 _includes/_root/decode-ways/Solution.java delete mode 100644 _includes/_root/distinct-subsequences/README.md delete mode 100644 _includes/_root/distinct-subsequences/Solution.java delete mode 100644 _includes/_root/divide-two-integers/README.md delete mode 100644 _includes/_root/divide-two-integers/Solution.java delete mode 100644 _includes/_root/dungeon-game/README.md delete mode 100644 _includes/_root/dungeon-game/Solution.java delete mode 100644 _includes/_root/edit-distance/README.md delete mode 100644 _includes/_root/edit-distance/Solution.java delete mode 100644 _includes/_root/evaluate-reverse-polish-notation/README.md delete mode 100644 _includes/_root/evaluate-reverse-polish-notation/Solution.java delete mode 100644 _includes/_root/excel-sheet-column-number/README.md delete mode 100644 _includes/_root/excel-sheet-column-number/Solution.java delete mode 100644 _includes/_root/excel-sheet-column-title/README.md delete mode 100644 _includes/_root/excel-sheet-column-title/Solution.java delete mode 100644 _includes/_root/factorial-trailing-zeroes/README.md delete mode 100644 _includes/_root/factorial-trailing-zeroes/Solution.java delete mode 100644 _includes/_root/find-minimum-in-rotated-sorted-array-ii/README.md delete mode 100644 _includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java delete mode 100644 _includes/_root/find-minimum-in-rotated-sorted-array/README.md delete mode 100644 _includes/_root/find-minimum-in-rotated-sorted-array/Solution.java delete mode 100644 _includes/_root/find-peak-element/README.md delete mode 100644 _includes/_root/find-peak-element/Solution.java delete mode 100644 _includes/_root/first-missing-positive/README.md delete mode 100644 _includes/_root/first-missing-positive/Solution.java delete mode 100644 _includes/_root/flatten-binary-tree-to-linked-list/README.md delete mode 100644 _includes/_root/flatten-binary-tree-to-linked-list/Solution.java delete mode 100644 _includes/_root/fraction-to-recurring-decimal/README.md delete mode 100644 _includes/_root/fraction-to-recurring-decimal/Solution.java delete mode 100644 _includes/_root/gas-station/README.md delete mode 100644 _includes/_root/gas-station/Solution.java delete mode 100644 _includes/_root/generate-parentheses/README.md delete mode 100644 _includes/_root/generate-parentheses/Solution.java delete mode 100644 _includes/_root/gray-code/README.md delete mode 100644 _includes/_root/gray-code/Solution.java delete mode 100644 _includes/_root/implement-strstr/README.md delete mode 100644 _includes/_root/implement-strstr/Solution.java delete mode 100644 _includes/_root/insert-interval/README.md delete mode 100644 _includes/_root/insert-interval/Solution.java delete mode 100644 _includes/_root/insertion-sort-list/README.md delete mode 100644 _includes/_root/insertion-sort-list/Solution.java delete mode 100644 _includes/_root/integer-to-roman/README.md delete mode 100644 _includes/_root/integer-to-roman/Solution.java delete mode 100644 _includes/_root/interleaving-string/README.md delete mode 100644 _includes/_root/interleaving-string/Solution.java delete mode 100644 _includes/_root/intersection-of-two-linked-lists/README.md delete mode 100644 _includes/_root/intersection-of-two-linked-lists/Solution.java delete mode 100644 _includes/_root/jump-game-ii/README.md delete mode 100644 _includes/_root/jump-game-ii/Solution.java delete mode 100644 _includes/_root/jump-game/README.md delete mode 100644 _includes/_root/jump-game/Solution.java delete mode 100644 _includes/_root/largest-number/README.md delete mode 100644 _includes/_root/largest-number/Solution.java delete mode 100644 _includes/_root/largest-rectangle-in-histogram/README.md delete mode 100644 _includes/_root/largest-rectangle-in-histogram/Solution.java delete mode 100644 _includes/_root/length-of-last-word/README.md delete mode 100644 _includes/_root/length-of-last-word/Solution.java delete mode 100644 _includes/_root/letter-combinations-of-a-phone-number/README.md delete mode 100644 _includes/_root/letter-combinations-of-a-phone-number/Solution.java delete mode 100644 _includes/_root/linked-list-cycle-ii/README.md delete mode 100644 _includes/_root/linked-list-cycle-ii/Solution.java delete mode 100644 _includes/_root/linked-list-cycle/README.md delete mode 100644 _includes/_root/linked-list-cycle/Solution.java delete mode 100644 _includes/_root/longest-common-prefix/README.md delete mode 100644 _includes/_root/longest-common-prefix/Solution.java delete mode 100644 _includes/_root/longest-consecutive-sequence/README.md delete mode 100644 _includes/_root/longest-consecutive-sequence/Solution.java delete mode 100644 _includes/_root/longest-palindromic-substring/README.md delete mode 100644 _includes/_root/longest-palindromic-substring/Solution.java delete mode 100644 _includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md delete mode 100644 _includes/_root/longest-substring-with-at-most-two-distinct-characters/Solution.java delete mode 100644 _includes/_root/longest-substring-without-repeating-characters/README.md delete mode 100644 _includes/_root/longest-substring-without-repeating-characters/Solution.java delete mode 100644 _includes/_root/longest-valid-parentheses/README.md delete mode 100644 _includes/_root/longest-valid-parentheses/Solution.java delete mode 100644 _includes/_root/lru-cache/README.md delete mode 100644 _includes/_root/lru-cache/Solution.java delete mode 100644 _includes/_root/majority-element/README.md delete mode 100644 _includes/_root/majority-element/Solution.java delete mode 100644 _includes/_root/max-points-on-a-line/README.md delete mode 100644 _includes/_root/max-points-on-a-line/Solution.java delete mode 100644 _includes/_root/maximal-rectangle/README.md delete mode 100644 _includes/_root/maximal-rectangle/Solution.java delete mode 100644 _includes/_root/maximum-depth-of-binary-tree/README.md delete mode 100644 _includes/_root/maximum-depth-of-binary-tree/Solution.java delete mode 100644 _includes/_root/maximum-gap/README.md delete mode 100644 _includes/_root/maximum-gap/Solution.java delete mode 100644 _includes/_root/maximum-product-subarray/README.md delete mode 100644 _includes/_root/maximum-product-subarray/Solution.java delete mode 100644 _includes/_root/maximum-subarray/README.md delete mode 100644 _includes/_root/maximum-subarray/Solution.java delete mode 100644 _includes/_root/median-of-two-sorted-arrays/README.md delete mode 100644 _includes/_root/median-of-two-sorted-arrays/Solution.java delete mode 100644 _includes/_root/merge-intervals/README.md delete mode 100644 _includes/_root/merge-intervals/Solution.java delete mode 100644 _includes/_root/merge-k-sorted-lists/README.md delete mode 100644 _includes/_root/merge-k-sorted-lists/Solution.java delete mode 100644 _includes/_root/merge-sorted-array/README.md delete mode 100644 _includes/_root/merge-sorted-array/Solution.java delete mode 100644 _includes/_root/merge-two-sorted-lists/README.md delete mode 100644 _includes/_root/merge-two-sorted-lists/Solution.java delete mode 100644 _includes/_root/min-stack/README.md delete mode 100644 _includes/_root/min-stack/Solution.java delete mode 100644 _includes/_root/minimum-depth-of-binary-tree/README.md delete mode 100644 _includes/_root/minimum-depth-of-binary-tree/Solution.java delete mode 100644 _includes/_root/minimum-path-sum/README.md delete mode 100644 _includes/_root/minimum-path-sum/Solution.java delete mode 100644 _includes/_root/minimum-window-substring/README.md delete mode 100644 _includes/_root/minimum-window-substring/Solution.java delete mode 100644 _includes/_root/missing-ranges/README.md delete mode 100644 _includes/_root/missing-ranges/Solution.java delete mode 100644 _includes/_root/multiply-strings/README.md delete mode 100644 _includes/_root/multiply-strings/Solution.java delete mode 100644 _includes/_root/n-queens-ii/README.md delete mode 100644 _includes/_root/n-queens-ii/Solution.java delete mode 100644 _includes/_root/n-queens/README.md delete mode 100644 _includes/_root/n-queens/Solution.java delete mode 100644 _includes/_root/next-permutation/README.md delete mode 100644 _includes/_root/next-permutation/Solution.java delete mode 100644 _includes/_root/one-edit-distance/README.md delete mode 100644 _includes/_root/one-edit-distance/Solution.java delete mode 100644 _includes/_root/palindrome-number/README.md delete mode 100644 _includes/_root/palindrome-number/Solution.java delete mode 100644 _includes/_root/palindrome-partitioning-ii/README.md delete mode 100644 _includes/_root/palindrome-partitioning-ii/Solution.java delete mode 100644 _includes/_root/palindrome-partitioning/README.md delete mode 100644 _includes/_root/palindrome-partitioning/Solution.java delete mode 100644 _includes/_root/partition-list/README.md delete mode 100644 _includes/_root/partition-list/Solution.java delete mode 100644 _includes/_root/pascals-triangle-ii/README.md delete mode 100644 _includes/_root/pascals-triangle-ii/Solution.java delete mode 100644 _includes/_root/pascals-triangle/README.md delete mode 100644 _includes/_root/pascals-triangle/Solution.java delete mode 100644 _includes/_root/path-sum-ii/README.md delete mode 100644 _includes/_root/path-sum-ii/Solution.java delete mode 100644 _includes/_root/path-sum/README.md delete mode 100644 _includes/_root/path-sum/Solution.java delete mode 100644 _includes/_root/permutation-sequence/README.md delete mode 100644 _includes/_root/permutation-sequence/Solution.java delete mode 100644 _includes/_root/permutations-ii/README.md delete mode 100644 _includes/_root/permutations-ii/Solution.java delete mode 100644 _includes/_root/permutations/README.md delete mode 100644 _includes/_root/permutations/Solution.java delete mode 100644 _includes/_root/plus-one/README.md delete mode 100644 _includes/_root/plus-one/Solution.java delete mode 100644 _includes/_root/populating-next-right-pointers-in-each-node-ii/README.md delete mode 100644 _includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java delete mode 100644 _includes/_root/populating-next-right-pointers-in-each-node/README.md delete mode 100644 _includes/_root/populating-next-right-pointers-in-each-node/Solution.java delete mode 100644 _includes/_root/powx-n/README.md delete mode 100644 _includes/_root/powx-n/Solution.java delete mode 100644 _includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md delete mode 100644 _includes/_root/read-n-characters-given-read4-ii-call-multiple-times/Solution.java delete mode 100644 _includes/_root/read-n-characters-given-read4/README.md delete mode 100644 _includes/_root/read-n-characters-given-read4/Solution.java delete mode 100644 _includes/_root/recover-binary-search-tree/README.md delete mode 100644 _includes/_root/recover-binary-search-tree/Solution.java delete mode 100644 _includes/_root/regular-expression-matching/README.md delete mode 100644 _includes/_root/regular-expression-matching/Solution.java delete mode 100644 _includes/_root/remove-duplicates-from-sorted-array-ii/README.md delete mode 100644 _includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java delete mode 100644 _includes/_root/remove-duplicates-from-sorted-array/README.md delete mode 100644 _includes/_root/remove-duplicates-from-sorted-array/Solution.java delete mode 100644 _includes/_root/remove-duplicates-from-sorted-list-ii/README.md delete mode 100644 _includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java delete mode 100644 _includes/_root/remove-duplicates-from-sorted-list/README.md delete mode 100644 _includes/_root/remove-duplicates-from-sorted-list/Solution.java delete mode 100644 _includes/_root/remove-element/README.md delete mode 100644 _includes/_root/remove-element/Solution.java delete mode 100644 _includes/_root/remove-nth-node-from-end-of-list/README.md delete mode 100644 _includes/_root/remove-nth-node-from-end-of-list/Solution.java delete mode 100644 _includes/_root/reorder-list/README.md delete mode 100644 _includes/_root/reorder-list/Solution.java delete mode 100644 _includes/_root/restore-ip-addresses/README.md delete mode 100644 _includes/_root/restore-ip-addresses/Solution.java delete mode 100644 _includes/_root/reverse-integer/README.md delete mode 100644 _includes/_root/reverse-integer/Solution.java delete mode 100644 _includes/_root/reverse-linked-list-ii/README.md delete mode 100644 _includes/_root/reverse-linked-list-ii/Solution.java delete mode 100644 _includes/_root/reverse-nodes-in-k-group/README.md delete mode 100644 _includes/_root/reverse-nodes-in-k-group/Solution.java delete mode 100644 _includes/_root/reverse-words-in-a-string/README.md delete mode 100644 _includes/_root/reverse-words-in-a-string/Solution.java delete mode 100644 _includes/_root/roman-to-integer/README.md delete mode 100644 _includes/_root/roman-to-integer/Solution.java delete mode 100644 _includes/_root/rotate-image/README.md delete mode 100644 _includes/_root/rotate-image/Solution.java delete mode 100644 _includes/_root/rotate-list/README.md delete mode 100644 _includes/_root/rotate-list/Solution.java delete mode 100644 _includes/_root/same-tree/README.md delete mode 100644 _includes/_root/same-tree/Solution.java delete mode 100644 _includes/_root/scramble-string/README.md delete mode 100644 _includes/_root/scramble-string/Solution.java delete mode 100644 _includes/_root/search-a-2d-matrix/README.md delete mode 100644 _includes/_root/search-a-2d-matrix/Solution.java delete mode 100644 _includes/_root/search-for-a-range/README.md delete mode 100644 _includes/_root/search-for-a-range/Solution.java delete mode 100644 _includes/_root/search-in-rotated-sorted-array-ii/README.md delete mode 100644 _includes/_root/search-in-rotated-sorted-array-ii/Solution.java delete mode 100644 _includes/_root/search-in-rotated-sorted-array/README.md delete mode 100644 _includes/_root/search-in-rotated-sorted-array/Solution.java delete mode 100644 _includes/_root/search-insert-position/README.md delete mode 100644 _includes/_root/search-insert-position/Solution.java delete mode 100644 _includes/_root/set-matrix-zeroes/README.md delete mode 100644 _includes/_root/set-matrix-zeroes/Solution.java delete mode 100644 _includes/_root/simplify-path/README.md delete mode 100644 _includes/_root/simplify-path/Solution.java delete mode 100644 _includes/_root/single-number-ii/README.md delete mode 100644 _includes/_root/single-number-ii/Solution.java delete mode 100644 _includes/_root/single-number/README.md delete mode 100644 _includes/_root/single-number/Solution.java delete mode 100644 _includes/_root/sort-colors/README.md delete mode 100644 _includes/_root/sort-colors/Solution.java delete mode 100644 _includes/_root/sort-list/README.md delete mode 100644 _includes/_root/sort-list/Solution.java delete mode 100644 _includes/_root/spiral-matrix-ii/README.md delete mode 100644 _includes/_root/spiral-matrix-ii/Solution.java delete mode 100644 _includes/_root/spiral-matrix/README.md delete mode 100644 _includes/_root/spiral-matrix/Solution.java delete mode 100644 _includes/_root/sqrtx/README.md delete mode 100644 _includes/_root/sqrtx/Solution.java delete mode 100644 _includes/_root/string-to-integer-atoi/README.md delete mode 100644 _includes/_root/string-to-integer-atoi/Solution.java delete mode 100644 _includes/_root/subsets-ii/README.md delete mode 100644 _includes/_root/subsets-ii/Solution.java delete mode 100644 _includes/_root/subsets/README.md delete mode 100644 _includes/_root/subsets/Solution.java delete mode 100644 _includes/_root/substring-with-concatenation-of-all-words/README.md delete mode 100644 _includes/_root/substring-with-concatenation-of-all-words/Solution.java delete mode 100644 _includes/_root/sudoku-solver/README.md delete mode 100644 _includes/_root/sudoku-solver/Solution.java delete mode 100644 _includes/_root/sum-root-to-leaf-numbers/README.md delete mode 100644 _includes/_root/sum-root-to-leaf-numbers/Solution.java delete mode 100644 _includes/_root/surrounded-regions/README.md delete mode 100644 _includes/_root/surrounded-regions/Solution.java delete mode 100644 _includes/_root/swap-nodes-in-pairs/README.md delete mode 100644 _includes/_root/swap-nodes-in-pairs/Solution.java delete mode 100644 _includes/_root/symmetric-tree/README.md delete mode 100644 _includes/_root/symmetric-tree/Solution.java delete mode 100644 _includes/_root/text-justification/README.md delete mode 100644 _includes/_root/text-justification/Solution.java delete mode 100644 _includes/_root/trapping-rain-water/README.md delete mode 100644 _includes/_root/trapping-rain-water/Solution.java delete mode 100644 _includes/_root/triangle/README.md delete mode 100644 _includes/_root/triangle/Solution.java delete mode 100644 _includes/_root/two-sum-ii-input-array-is-sorted/README.md delete mode 100644 _includes/_root/two-sum-ii-input-array-is-sorted/Solution.java delete mode 100644 _includes/_root/two-sum-iii-data-structure-design/README.md delete mode 100644 _includes/_root/two-sum-iii-data-structure-design/Solution.java delete mode 100644 _includes/_root/two-sum/README.md delete mode 100644 _includes/_root/two-sum/Solution.java delete mode 100644 _includes/_root/unique-binary-search-trees-ii/README.md delete mode 100644 _includes/_root/unique-binary-search-trees-ii/Solution.java delete mode 100644 _includes/_root/unique-binary-search-trees/README.md delete mode 100644 _includes/_root/unique-binary-search-trees/Solution.java delete mode 100644 _includes/_root/unique-paths-ii/README.md delete mode 100644 _includes/_root/unique-paths-ii/Solution.java delete mode 100644 _includes/_root/unique-paths/README.md delete mode 100644 _includes/_root/unique-paths/Solution.java delete mode 100644 _includes/_root/valid-number/README.md delete mode 100644 _includes/_root/valid-number/Solution.java delete mode 100644 _includes/_root/valid-palindrome/README.md delete mode 100644 _includes/_root/valid-palindrome/Solution.java delete mode 100644 _includes/_root/valid-parentheses/README.md delete mode 100644 _includes/_root/valid-parentheses/Solution.java delete mode 100644 _includes/_root/valid-sudoku/README.md delete mode 100644 _includes/_root/valid-sudoku/Solution.java delete mode 100644 _includes/_root/validate-binary-search-tree/README.md delete mode 100644 _includes/_root/validate-binary-search-tree/Solution.java delete mode 100644 _includes/_root/wildcard-matching/README.md delete mode 100644 _includes/_root/wildcard-matching/Solution.java delete mode 100644 _includes/_root/word-break-ii/README.md delete mode 100644 _includes/_root/word-break-ii/Solution.java delete mode 100644 _includes/_root/word-break/README.md delete mode 100644 _includes/_root/word-break/Solution.java delete mode 100644 _includes/_root/word-ladder-ii/README.md delete mode 100644 _includes/_root/word-ladder-ii/Solution.java delete mode 100644 _includes/_root/word-ladder/README.md delete mode 100644 _includes/_root/word-ladder/Solution.java delete mode 100644 _includes/_root/word-search/README.md delete mode 100644 _includes/_root/word-search/Solution.java delete mode 100644 _includes/_root/zigzag-conversion/README.md delete mode 100644 _includes/_root/zigzag-conversion/Solution.java diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..a5b4b4f --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "_includes/_root"] + path = _includes/_root + url = https://github.com/tg123/leetcode.git + branch = gh-pages diff --git a/_includes/_root b/_includes/_root new file mode 160000 index 0000000..a2df120 --- /dev/null +++ b/_includes/_root @@ -0,0 +1 @@ +Subproject commit a2df1209cc0d85bdc827cb7a22b9dbafd4a2ccc0 diff --git a/_includes/_root/3sum-closest/README.md b/_includes/_root/3sum-closest/README.md deleted file mode 100644 index ea69150..0000000 --- a/_includes/_root/3sum-closest/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Variant of [3Sum](../3sum) - -Just update the closest number each loop. diff --git a/_includes/_root/3sum-closest/Solution.java b/_includes/_root/3sum-closest/Solution.java deleted file mode 100644 index 1554858..0000000 --- a/_includes/_root/3sum-closest/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -public class Solution { - public int threeSumClosest(int[] num, int target) { - - if(num.length < 3) return 0; - - Arrays.sort(num); - - int pneg = 0 , ppos = num.length - 1; - - int closest = num[0] + num[1] + num[2]; - - while(ppos > 0){ - while(pneg < ppos){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(Math.abs(target - (num[i] + sum)) < Math.abs(target - closest) ){ - closest = num[i] + sum; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return closest; - } -} \ No newline at end of file diff --git a/_includes/_root/3sum/README.md b/_includes/_root/3sum/README.md deleted file mode 100644 index 39d344f..0000000 --- a/_includes/_root/3sum/README.md +++ /dev/null @@ -1,32 +0,0 @@ -## Guessing - -sum of three number equals to zero, there must be at least one `negative number` and one `positive number`. - -make the input array sorted, `negative numbers` should be on the left end and `positive numbers` should be on the right end. - -choose a `negative number` and a `positive number`, and search from the `negative number` to the positive number, find a number: - -such that `the number` + `negative number` + `positive number` = 0. - -if there is no `negative number` or `positive number`, we can sure no three sum equals to zero. - - -``` - -sort input array num - -n = 0 -p = end of array - -while num[n] is negative and num[p] is positive - - foreach i between n and p - if num[i] + num[n] + num[p] == 0 - add result to collection - reset n = 0 - p = p - 1 - - try another loop - - -``` diff --git a/_includes/_root/3sum/Solution.java b/_includes/_root/3sum/Solution.java deleted file mode 100644 index a158e28..0000000 --- a/_includes/_root/3sum/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -public class Solution { - public List> threeSum(int[] num) { - - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - - int pneg = 0 , ppos = num.length - 1; - - - while(ppos > 0 && num[ppos] >= 0){ - while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ - int sum = num[pneg]; - sum += num[ppos]; - - for(int i = pneg + 1; i < ppos; i++){ - if(num[i] + sum == 0){ - found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); - - break; - } - } - - int old = num[pneg]; - while(pneg < ppos && num[pneg] == old) pneg++; - } - - pneg = 0; - - int old = num[ppos]; - while(ppos > 0 && num[ppos] == old) ppos--; - } - - - return found; - - } -} diff --git a/_includes/_root/4sum/README.md b/_includes/_root/4sum/README.md deleted file mode 100644 index 6f9e7bd..0000000 --- a/_includes/_root/4sum/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## [Space-time tradeoff](http://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff) - -Brute force will solve this problem, but leetcode will reject because of time limit. - -## [Two Sum](../two-sum) + [Two Sum](../two-sum) = 4 Sum - - * build two number's sum cache `{ 42 : [index1, index2], ... }` - * foreach `key` in cache and `sum - key` in cache, add the cartesian product of the values to the result collection diff --git a/_includes/_root/4sum/Solution.java b/_includes/_root/4sum/Solution.java deleted file mode 100644 index 2992b72..0000000 --- a/_includes/_root/4sum/Solution.java +++ /dev/null @@ -1,83 +0,0 @@ -public class Solution { - - static class TwoSum { - int index1; - int index2; - - boolean overlap(TwoSum other){ - if(this == other) return true; - - if(index1 == other.index1) return true; - if(index2 == other.index1) return true; - - if(index1 == other.index2) return true; - if(index2 == other.index2) return true; - - return false; - } - } - - public List> fourSum(int[] num, int target) { - ArrayList> found = new ArrayList>(); - - if(num.length < 4) return found; - - HashMap> cache = new HashMap>(); - - Arrays.sort(num); - - for(int i = 0; i < num.length; i++){ - for(int j = i + 1; j < num.length; j++){ - - int s = num[i] + num[j]; - TwoSum t = new TwoSum(); - - t.index1 = i; - t.index2 = j; - - ArrayList l = cache.get(s); - if(l == null){ - l = new ArrayList(); - cache.put(s, l); - } - - l.add(t); - } - } - - HashSet block = new HashSet(); - - for(Integer a : cache.keySet()){ - Integer b = target - a; - - ArrayList lsb = cache.get(b); - if(lsb != null){ - ArrayList lsa = cache.get(a); - - for(TwoSum sa : lsa) - for(TwoSum sb : lsb){ - - if(sa.overlap(sb)) continue; - - Integer[] sol = new Integer[]{num[sa.index1], num[sa.index2], num[sb.index1], num[sb.index2]}; - Arrays.sort(sol); - - String uid = Arrays.toString(sol); - if(!block.contains(uid)){ - found.add(Arrays.asList(sol)); - - block.add(uid); - } - - - } - - cache.put(a, null); - cache.put(b, null); - } - } - - - return found; - } -} diff --git a/_includes/_root/add-binary/README.md b/_includes/_root/add-binary/README.md deleted file mode 100644 index 5ff1379..0000000 --- a/_includes/_root/add-binary/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Advanced [Plus One](../plus-one) - - * Plus many Ones this time - * binary vs decimal (carry is `digit[i] / 2`) diff --git a/_includes/_root/add-binary/Solution.java b/_includes/_root/add-binary/Solution.java deleted file mode 100644 index 31c8933..0000000 --- a/_includes/_root/add-binary/Solution.java +++ /dev/null @@ -1,47 +0,0 @@ -public class Solution { - - int toint(char c){ - if(c >= '0') return c - '0'; - return 0; - } - - int toint(char[] chars, int index){ - if(index < chars.length && index >=0 ) return toint(chars[index]); - return 0; - } - - public String addBinary(String a, String b) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(a == null || b == null) return null; - - char[] ca = a.toCharArray(); - char[] cb = b.toCharArray(); - - int n = Math.max(ca.length, cb.length); - - int[] s = new int[n + 1]; - - - //ca = Arrays.copyOf(ca , n); - //cb = Arrays.copyOf(cb , n); - - for(int i = 0 ; i=0; i--){ - ss = ss + s[i]; - } - - if ( s[n] == 1 ) ss = "1" + ss; - - return ss; - - } -} \ No newline at end of file diff --git a/_includes/_root/add-two-numbers/README.md b/_includes/_root/add-two-numbers/README.md deleted file mode 100644 index 9801e51..0000000 --- a/_includes/_root/add-two-numbers/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Decimal and Linked list version of [Add Binary](../add-binary) - -Code may look like the same, linked list is just another kind of array. diff --git a/_includes/_root/add-two-numbers/Solution.java b/_includes/_root/add-two-numbers/Solution.java deleted file mode 100644 index c66f5d7..0000000 --- a/_includes/_root/add-two-numbers/Solution.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - ListNode r = new ListNode(0); - ListNode h = r; - ListNode beforeend = r; - - while(l1 !=null && l2 != null){ - r.val += l1.val + l2.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - l1 = l1.next; - l2 = l2.next; - } - - ListNode rest; - if (l1 == null) rest = l2; else rest = l1; - - while(rest != null){ - r.val += rest.val; - - r.next = new ListNode(r.val / 10); - r.val %= 10; - - beforeend = r; - r = r.next; - rest = rest.next; - } - - if(beforeend.next != null && beforeend.next.val == 0) beforeend.next = null; - - return h; - } -} \ No newline at end of file diff --git a/_includes/_root/anagrams/README.md b/_includes/_root/anagrams/README.md deleted file mode 100644 index 8071721..0000000 --- a/_includes/_root/anagrams/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Mapping many to one - -Strings that are [anagrams](http://en.wikipedia.org/wiki/Anagram) can transform to the same string. - -`mary` and `army` are anagrams. and `amry` and them are also anagrams. -so just put all strings into a `HashMap` with key of same mapping rule, then find out all the values `count > 1`. - diff --git a/_includes/_root/anagrams/Solution.java b/_includes/_root/anagrams/Solution.java deleted file mode 100644 index 4bea62c..0000000 --- a/_includes/_root/anagrams/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -public class Solution { - public ArrayList anagrams(String[] strs) { - ArrayList found = new ArrayList(); - - HashMap> box = new HashMap>(); - - for(String str : strs){ - char[] cstr = str.toCharArray(); - Arrays.sort(cstr); - - String key = new String(cstr); - - ArrayList c = box.get(key); - if(c == null){ - box.put(key , new ArrayList()); - } - - c = box.get(key); - c.add(str); - - } - - for(ArrayList s : box.values()){ - - if(s.size() > 1){ - found.addAll(s); - } - - } - - return found; - } -} \ No newline at end of file diff --git a/_includes/_root/balanced-binary-tree/README.md b/_includes/_root/balanced-binary-tree/README.md deleted file mode 100644 index 892892c..0000000 --- a/_includes/_root/balanced-binary-tree/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Definition - -``` - -Balanced(T) = Balanced(T.left) && Balanced(T.right) - && ABS(Height(T.left) - Height(T.right)) <= 1 - -``` - diff --git a/_includes/_root/balanced-binary-tree/Solution.java b/_includes/_root/balanced-binary-tree/Solution.java deleted file mode 100644 index 9835271..0000000 --- a/_includes/_root/balanced-binary-tree/Solution.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int height(TreeNode root){ - if(root == null) - return 0; - else - return Math.max(height(root.left), height(root.right)) + 1; - } - - public boolean isBalanced(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(root == null) return true; - - return - Math.abs(height(root.left) - height(root.right)) <=1 && - isBalanced(root.left) && isBalanced(root.right); - - //return isBalanced() - } -} \ No newline at end of file diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-ii/README.md b/_includes/_root/best-time-to-buy-and-sell-stock-ii/README.md deleted file mode 100644 index 4da35f1..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock-ii/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Sell whenever there is profit - -An easy problem. each time got a new price, sell all if there is profit. -Then buy and wait for another price jump. - - - diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java deleted file mode 100644 index d037df7..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock-ii/Solution.java +++ /dev/null @@ -1,24 +0,0 @@ -public class Solution { - public int maxProfit(int[] prices) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(prices.length <= 1) return 0; - - int profit = 0; - - int hold = prices[0]; - - for(int i = 1; i < prices.length; i++){ - - - if(hold < prices[i]){ - profit += prices[i] - hold; // sell - - } - - hold = prices[i]; - } - - return profit; - } -} \ No newline at end of file diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-iii/README.md b/_includes/_root/best-time-to-buy-and-sell-stock-iii/README.md deleted file mode 100644 index 1fc6d4f..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock-iii/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## [Best Time to Buy and Sell Stock](../best-time-to-buy-and-sell-stock) Twice - - -``` - | - | * * - * | * * * - * * | * * -* * |* * - * | * * * - * *| * * - | * - | - - i - - -``` - -If prices are divide into two parts at position `i`, we can treat each part as a `0..i` [Best Time to Buy and Sell Stock](../best-time-to-buy-and-sell-stock) and `i..end` [Best Time to Buy and Sell Stock](../best-time-to-buy-and-sell-stock). - - -## Brute force `i` - -As we do not know which `i` will be the most profit one, just try test `i` and save them. - - -``` -left : array -right : array - -foreach i in prices - - left[i] = Best Time to Buy and Sell Stock 0..i - right[i] = Best Time to Buy and Sell Stock i..end - -``` - -maxProfit is MAX(`left[i] + right[i]`) diff --git a/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java deleted file mode 100644 index 29c2e8c..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock-iii/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -public class Solution { - public int maxProfit(int[] prices) { - if(prices.length < 2) return 0; - - int[] left = new int[prices.length]; - int[] right = new int[prices.length]; - - - int left_min = prices[0]; - - for(int i = 1; i < prices.length; i++){ - left_min = Math.min(left_min, prices[i]); - left[i] = Math.max(prices[i] - left_min, left[i - 1]); - } - - int right_max = prices[prices.length - 1]; - - for(int i = prices.length - 2; i >= 0; i--){ - right_max = Math.max(right_max, prices[i]); - right[i] = Math.max(right_max - prices[i], right[i + 1]); - } - - int m = 0; - - for(int i = 0; i < prices.length; i++){ - m = Math.max(m, left[i] + right[i]); - } - - return m; - - } -} diff --git a/_includes/_root/best-time-to-buy-and-sell-stock/README.md b/_includes/_root/best-time-to-buy-and-sell-stock/README.md deleted file mode 100644 index 3eb078a..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## Buy low and sell high - - * find the lowest point in the prices - * find the highest point in the prices - * most important: the lowest point must not behind the highest point - - -so walk through the `prices`, see check if there is more profit at current point. (`profit = current - lowest before current`) - -``` - -foreach p in prices - - lowest = MIN(p, lowest) - - current_profit = p - lowest - - maxprofit = MAX(maxprofit, current_profit) - -``` diff --git a/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java b/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java deleted file mode 100644 index 78e581c..0000000 --- a/_includes/_root/best-time-to-buy-and-sell-stock/Solution.java +++ /dev/null @@ -1,17 +0,0 @@ -public class Solution { - public int maxProfit(int[] prices) { - - int max = 0; - - int lowest = Integer.MAX_VALUE; - - for(int p : prices){ - - lowest = Math.min(lowest, p); - - max = Math.max(p - lowest, max); - } - - return max; - } -} diff --git a/_includes/_root/binary-search-tree-iterator/README.md b/_includes/_root/binary-search-tree-iterator/README.md deleted file mode 100644 index 411fa1d..0000000 --- a/_includes/_root/binary-search-tree-iterator/README.md +++ /dev/null @@ -1,43 +0,0 @@ -## [Yielding](http://en.wikipedia.org/wiki/Generator_(computer_programming)) and [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal) - -In the problem [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), -we solved it by simlating the function call. - -Only a bit different this time, -when the caller calls `next()`: - - 1. just execute to next value returns - 1. save the stack and next address (state) - 1. yield the node value and return control to caller - -actions above is the `while` body part in the [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal). - -### Edge cases in `hasNext()` - -like [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal), -when the stack is empty, there are no more nodes. - -However, if only one state left in the stack and the address of the state is `POST`, -we need some additional check. - -`POST` state here means to deal with right node of current node (value already yeild to caller when `IN` step). -sometimes, the node does not have right child. we should return false when caller ask `hasNext()`. - -## Why it is `O(h)` in space - -the space here used in my solution is the `stack`. -only tree nodes with left child will consume a space in the `stack`. -because nodes without left child can be yield to caller directly. - -Worst case - -``` - 1 - / - 2 - / - 3 -``` - -here we have to save `node 1` and `node 2` before we found `node 3`. -but the space used in stack will be no more than 3. diff --git a/_includes/_root/binary-search-tree-iterator/Solution.java b/_includes/_root/binary-search-tree-iterator/Solution.java deleted file mode 100644 index 5776345..0000000 --- a/_includes/_root/binary-search-tree-iterator/Solution.java +++ /dev/null @@ -1,91 +0,0 @@ -/** -* Definition for binary tree -* public class TreeNode { -* int val; -* TreeNode left; -* TreeNode right; -* TreeNode(int x) { val = x; } -* } -*/ - -public class BSTIterator { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - Deque stack = new LinkedList(); - - public BSTIterator(TreeNode root) { - if(root != null) { - stack.push(new StackState(root)); - } - } - - /** @return whether we have a next smallest number */ - public boolean hasNext() { - if(!stack.isEmpty()){ - StackState current = stack.pop(); - switch(current.returnAddress){ - case PRE: - case IN: - stack.push(current); - return true; - - case POST: - if(current.param.right != null){ - stack.push(new StackState(current.param.right)); - return true; - } - } - return hasNext(); - } - return false; - } - - /** @return the next smallest number */ - public int next() { - - StackState current = stack.pop(); - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - break; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - stack.push(current); - return current.param.val; - - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - break; - } - } - return next(); - } -} - -/** -* Your BSTIterator will be called like this: -* BSTIterator i = new BSTIterator(root); -* while (i.hasNext()) v[f()] = i.next(); -*/ diff --git a/_includes/_root/binary-tree-inorder-traversal/README.md b/_includes/_root/binary-tree-inorder-traversal/README.md deleted file mode 100644 index 12d1924..0000000 --- a/_includes/_root/binary-tree-inorder-traversal/README.md +++ /dev/null @@ -1,100 +0,0 @@ -## Definition - - * inorder(node.left) - * visit node - * inorder(node.right) - -It is easy to write a recursive version. - -## Convert to an iterative version - -There are a lot of articles about how to do this using a stack, but, I have no enough memory to understand why they are using stack like that. -As a result, I am going to write a `function call` simulating verison. - - -### What happens when call to a function and return from a function - -Call - - * save all local vars - * save current code address (continue executing after callee returned) - * put params somewhere - * jump to the function - -Return - - * retore all local vars - * jump to saved caller code address - - -### Simulating address - -`switch` is a good idea. - -``` -(function entrance) - - // return or new call start - - take params from somewhere - take saved address from somewhere - - switch saved address - Line 1: - - do something - - Line 100: - - do someting - - // making call - save some var - save next address 250 - - put some param for new call - jump to (function entrance) - - - Line 250: - - do something - -``` - -### Back to the problem - - * Use a stack to save `state`, a `state` contains a `param TreeNode` and a `return address`. - * Use a loop to execute all `state` (simulating recursive function call) - * whenever there need a new call to function - * push current `state` to stack - * create and push a new `state` with param to stack - * jump to loop begin - -``` -while stack is not empty - - current = stack.pop() - - switch current.returnAddress - - PRE: - stack.push current - - new state { returnAddress = IN, param = current.left } - stack.push new state - - IN: - visit current.param - - - POST: - - stack.push current - - new state { returnAddress = DONOTHING, param = current.right } - stack.push new state - ... - -``` - diff --git a/_includes/_root/binary-tree-inorder-traversal/Solution.java b/_includes/_root/binary-tree-inorder-traversal/Solution.java deleted file mode 100644 index 9a01a4a..0000000 --- a/_includes/_root/binary-tree-inorder-traversal/Solution.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList inorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - rt.add(current.param.val); - - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - } -} diff --git a/_includes/_root/binary-tree-level-order-traversal-ii/README.md b/_includes/_root/binary-tree-level-order-traversal-ii/README.md deleted file mode 100644 index 8b2e125..0000000 --- a/_includes/_root/binary-tree-level-order-traversal-ii/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Same as [Binary Tree Level Order Traversal](../binary-tree-level-order-traversal) - -The only difference is up side down. So use a stack for output. diff --git a/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java b/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java deleted file mode 100644 index de6dea7..0000000 --- a/_includes/_root/binary-tree-level-order-traversal-ii/Solution.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrderBottom(TreeNode root) { - LinkedList> rt = new LinkedList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.push(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - } -} diff --git a/_includes/_root/binary-tree-level-order-traversal/README.md b/_includes/_root/binary-tree-level-order-traversal/README.md deleted file mode 100644 index cc9c5cf..0000000 --- a/_includes/_root/binary-tree-level-order-traversal/README.md +++ /dev/null @@ -1,77 +0,0 @@ -## [Breadth-first search](http://en.wikipedia.org/wiki/Breadth-first_search) - -BSF has its common pattern. - -Pattern for problems with many steps and each step has many ways to next step: - -``` -a queue stores [step0, step1, step2, ...] - -queue.add(first step) - -while queue is not empty - - current_step = queue.poll() - - // do something here with current_step - // like counting - - foreah step in current_step can jump to - queue.add(step) - - - -``` - -## Apply the pattern - -It is easy to search through a binary tree using BSF. - -``` -queue.add(root) - -while queue is not empty - - current_node = queue.poll() - - add current_node.value to current level collections - - queue.add(current_node.left) - queue.add(current_node.right) - -``` - -### How to know which level current node should be added to - - -use a dummy node as a `separator` into the queue, whenever polling a `separator` from the queue, we know that a level is end. - -codes may be like below - -``` -queue.add(root) -queue.add(SEP) - - -while queue is not empty - - current_node = queue.poll() - - if current_node is SEP - - // new level is start - reset current_level collection - - queue.add(SEP) // here is added to the end of current level - - stop if only SEP in the queue - - else - - add current_node.value to current_level collection - - queue.add(current_node.left) - queue.add(current_node.right) - -``` - diff --git a/_includes/_root/binary-tree-level-order-traversal/Solution.java b/_includes/_root/binary-tree-level-order-traversal/Solution.java deleted file mode 100644 index 714da2d..0000000 --- a/_includes/_root/binary-tree-level-order-traversal/Solution.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> levelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - ArrayList level = new ArrayList(); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - rt.add(new ArrayList(level)); // copy - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node.val); - - if(node.left != null) queue.addLast(node.left); - if(node.right != null) queue.addLast(node.right); - } - } - - return rt; - - } -} diff --git a/_includes/_root/binary-tree-maximum-path-sum/README.md b/_includes/_root/binary-tree-maximum-path-sum/README.md deleted file mode 100644 index cb5d2fb..0000000 --- a/_includes/_root/binary-tree-maximum-path-sum/README.md +++ /dev/null @@ -1,83 +0,0 @@ -## What will the maximum path look like - -Though paths can be starting from any node and end at any node, the appearances only can be: - - * Appearance 1 - -``` - * - / \ - * * - / \ - * * - / \ -S * - \ - E -``` - - * Appearance 2 - -``` - E - / - * - / - * - / -S -``` - -* Appearance 3 - -``` -S - \ - * - \ - * - \ - * - \ - E -``` - -### Note - -Appearances above are only talking about `TRUNK`. - -Treat the path below as Appearance 1 - -``` - * - / \ - * * - / \ - * * - \ / - S * - \ - E -``` - - -## Tree Version of [Maximum Subarray](../maximum-subarray) - - * Appearance 2/3 - -These two appearances are easy to understand and to build a path, just take the maximum node. -like `Maximum Subarray`, if the sum goes below `0`, forget the old nodes. - - * Appearance 1 - -If a node's left child or right child is less than `0`, drop it, then the node becomes `Appearance 2/3`. - -If both the left child and right child are positive, just add them together, `maxPathSum(node.left) + node.val + maxPathSum(node.right)` will be the `maxPathSum` which contains that node. - - -## Put them together - -As we know how to find the `maxPathSum` of any node, we can go through the tree and update the max value. - - - diff --git a/_includes/_root/binary-tree-maximum-path-sum/Solution.java b/_includes/_root/binary-tree-maximum-path-sum/Solution.java deleted file mode 100644 index fca1696..0000000 --- a/_includes/_root/binary-tree-maximum-path-sum/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int max; - - int sum(TreeNode root){ - if(root == null) return 0; - - int left = sum(root.left); - int right = sum(root.right); - - left = Math.max(left, 0); - right = Math.max(right, 0); - - int sum = root.val + left + right; - max = Math.max(max, sum); - - return Math.max(left, right) + root.val; - } - - public int maxPathSum(TreeNode root) { - - max = Integer.MIN_VALUE; - sum(root); - - return max; - } -} \ No newline at end of file diff --git a/_includes/_root/binary-tree-postorder-traversal/README.md b/_includes/_root/binary-tree-postorder-traversal/README.md deleted file mode 100644 index c697636..0000000 --- a/_includes/_root/binary-tree-postorder-traversal/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Some as [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal) - - * postorder(node.left) - * postorder(node.right) - * visit node diff --git a/_includes/_root/binary-tree-postorder-traversal/Solution.java b/_includes/_root/binary-tree-postorder-traversal/Solution.java deleted file mode 100644 index 989a06e..0000000 --- a/_includes/_root/binary-tree-postorder-traversal/Solution.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList postorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - - case POST: - current.returnAddress = ReturnAddress.DONE; - - rt.add(current.param.val); - - default: - break; - } - } - - - return rt; - } -} diff --git a/_includes/_root/binary-tree-preorder-traversal/README.md b/_includes/_root/binary-tree-preorder-traversal/README.md deleted file mode 100644 index 0ba02be..0000000 --- a/_includes/_root/binary-tree-preorder-traversal/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Some as [Binary Tree Inorder Traversal](../binary-tree-inorder-traversal) - - * visit node - * preorder(node.left) - * preorder(node.right) diff --git a/_includes/_root/binary-tree-preorder-traversal/Solution.java b/_includes/_root/binary-tree-preorder-traversal/Solution.java deleted file mode 100644 index 6172150..0000000 --- a/_includes/_root/binary-tree-preorder-traversal/Solution.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static enum ReturnAddress { - PRE, IN, POST, DONE; - } - - static class StackState { - ReturnAddress returnAddress = ReturnAddress.PRE; - TreeNode param; - - StackState(TreeNode param){ - this.param = param; - } - } - - public ArrayList preorderTraversal(TreeNode root) { - - ArrayList rt = new ArrayList(); - - Deque stack = new LinkedList(); - - if(root != null) - stack.push(new StackState(root)); - - while(!stack.isEmpty()){ - - StackState current = stack.pop(); - - switch(current.returnAddress){ - case PRE: - current.returnAddress = ReturnAddress.IN; - rt.add(current.param.val); - - case IN: - current.returnAddress = ReturnAddress.POST; - - if(current.param.left != null){ - stack.push(current); - stack.push(new StackState(current.param.left)); - continue; - } - case POST: - current.returnAddress = ReturnAddress.DONE; - - if(current.param.right != null){ - stack.push(current); - stack.push(new StackState(current.param.right)); - continue; - } - default: - break; - } - } - - - return rt; - - } -} diff --git a/_includes/_root/binary-tree-upside-down/README.md b/_includes/_root/binary-tree-upside-down/README.md deleted file mode 100644 index f23477e..0000000 --- a/_includes/_root/binary-tree-upside-down/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## $ 15 - -This is the first paid problem ever. `Nov 17` - -## Inorder travel - -I found it just looks like result of an inorder travel on the tree - -``` - 1 - / \ - 2 3 - / \ -4 5 -``` - -Inorder: 4 2 5 1 3 - -Result: - -``` - 4 - / \ - 5 2 - / \ - 3 1 -``` - -we can build the new tree using the inorder result easily. - -### Difference from regular inorder travel - - * No need to inorder right child, because it must be leaf or empty - * Empty right child should be added to the result if left child is not empty. This is to recovery the empty node in the new tree. - - - diff --git a/_includes/_root/binary-tree-upside-down/Solution.java b/_includes/_root/binary-tree-upside-down/Solution.java deleted file mode 100644 index 8632e7b..0000000 --- a/_includes/_root/binary-tree-upside-down/Solution.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - LinkedList queue = new LinkedList(); - - void inOrder(TreeNode root){ - - if(root == null) return; - - inOrder(root.left); - - queue.add(root); - - if(root.left != null) { - queue.add(root.right); - } - - - root.left = null; - root.right = null; - } - - public TreeNode UpsideDownBinaryTree(TreeNode root) { - - inOrder(root); - - TreeNode newRoot = queue.poll(); - - root = newRoot; - - while(!queue.isEmpty()){ - root.right = queue.poll(); - root.left = queue.poll(); - - root = root.right; - } - - return newRoot; - } -} diff --git a/_includes/_root/binary-tree-zigzag-level-order-traversal/README.md b/_includes/_root/binary-tree-zigzag-level-order-traversal/README.md deleted file mode 100644 index 0d4748d..0000000 --- a/_includes/_root/binary-tree-zigzag-level-order-traversal/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Improved version of [Binary Tree Level Order Traversal](../binary-tree-level-order-traversal) - -Add a `direction` for zigzag traversal. - - * change `direction` when level ends. - * add to the level head or tail depends on `direction` diff --git a/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java b/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java deleted file mode 100644 index b20f5f2..0000000 --- a/_includes/_root/binary-tree-zigzag-level-order-traversal/Solution.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public List> zigzagLevelOrder(TreeNode root) { - - ArrayList> rt = new ArrayList>(); - - if(root == null) return rt; - - final TreeNode END = new TreeNode(0); - - Deque queue = new LinkedList(); - - queue.add(root); - queue.add(END); - - boolean direction = true; // true for left -> right , false for right -> left - - Deque level = new LinkedList(); - - while(!queue.isEmpty()){ - TreeNode current = queue.poll(); - - if(current == END){ - - direction = !direction; - rt.add(new ArrayList(level)); // copy - - level.clear(); - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - if(direction){ // true for left -> right , false for right -> left - level.addLast(current.val); - }else{ - level.addFirst(current.val); - } - - - if(current.left != null) queue.add(current.left); - if(current.right != null) queue.add(current.right); - - } - } - - return rt; - - } -} diff --git a/_includes/_root/candy/README.md b/_includes/_root/candy/README.md deleted file mode 100644 index 9501213..0000000 --- a/_includes/_root/candy/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Two passes - - * from left to right - - Ensure any child has more candies than the child on his left - - - * from right to left - - Ensure any child has more candies than the child on his right - - diff --git a/_includes/_root/candy/Solution.java b/_includes/_root/candy/Solution.java deleted file mode 100644 index 1de13ae..0000000 --- a/_includes/_root/candy/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -public class Solution { - public int candy(int[] ratings) { - - - int[] candies = new int[ratings.length]; - - Arrays.fill(candies, 1); - - for(int i = 1; i < candies.length; i++){ - if(ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) - candies[i] = candies[i - 1] + 1; - } - - for(int i = candies.length - 2; i >= 0; i--){ - if(ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) - candies[i] = candies[i + 1] + 1; - } - - int s = 0; - for(int c : candies) - s += c; - - return s; - - } -} \ No newline at end of file diff --git a/_includes/_root/climbing-stairs/README.md b/_includes/_root/climbing-stairs/README.md deleted file mode 100644 index 6212e3d..0000000 --- a/_includes/_root/climbing-stairs/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Recursion - - * 0 stair has 0 way - * 1 stair has 1 way - * 2 stairs have 2 ways (0->1->2, 0->2) - * 3 stairs have 3 ways (0->1->2->3, 0->2->3, 0-1->3) - * ... - -stair `3` come be jump from stair `1`(1 ways from 0 to here) and stair `2`(2 ways from 0 to here). - -so... - -``` -climbStairs(n) = climbStairs(n - 1) + climbStairs(n - 2) -``` - -## [Space-time tradeoff](http://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff) - -put stair `i` into cache. diff --git a/_includes/_root/climbing-stairs/Solution.java b/_includes/_root/climbing-stairs/Solution.java deleted file mode 100644 index 8706e30..0000000 --- a/_includes/_root/climbing-stairs/Solution.java +++ /dev/null @@ -1,19 +0,0 @@ -public class Solution { - public int climbStairs(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - int[] step = new int[Math.max(n + 1, 3)]; - - - step[0] = 0; - step[1] = 1; - step[2] = 2; - - for(int i = 3; i <= n; i++){ - step[i] = step[i - 1] + step[i - 2]; - } - - return step[n]; - } -} \ No newline at end of file diff --git a/_includes/_root/clone-graph/README.md b/_includes/_root/clone-graph/README.md deleted file mode 100644 index e57ea40..0000000 --- a/_includes/_root/clone-graph/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Clone Vertices And Edges - -two steps and esay to understand - - 1. Clone Vertex to new one - 1. Draw edges to new vertices like the original graph diff --git a/_includes/_root/clone-graph/Solution.java b/_includes/_root/clone-graph/Solution.java deleted file mode 100644 index 11a8222..0000000 --- a/_includes/_root/clone-graph/Solution.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Definition for undirected graph. - * class UndirectedGraphNode { - * int label; - * ArrayList neighbors; - * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } - * }; - */ -public class Solution { - public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { - - if(node == null) return null; - - // visit - HashMap clone = new HashMap(); - - Deque queue = new LinkedList(); - - queue.add(node); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!clone.containsKey(n)){ - clone.put(n, new UndirectedGraphNode(n.label)); - - for(UndirectedGraphNode neighbor : n.neighbors){ - queue.add(neighbor); - } - } - } - - queue.add(node); - HashSet visit = new HashSet(); - - while(queue.size() > 0){ - - UndirectedGraphNode n = queue.poll(); - if(!visit.contains(n)){ - visit.add(n); - - UndirectedGraphNode c = clone.get(n); - - for(UndirectedGraphNode neighbor : n.neighbors){ - c.neighbors.add(clone.get(neighbor)); - queue.add(neighbor); - } - } - } - - return clone.get(node); - - } -} \ No newline at end of file diff --git a/_includes/_root/combination-sum-ii/README.md b/_includes/_root/combination-sum-ii/README.md deleted file mode 100644 index 1143ef5..0000000 --- a/_includes/_root/combination-sum-ii/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Improved version of [Combination Sum](../combination-sum) - -This time, add a set to block duplicates. diff --git a/_includes/_root/combination-sum-ii/Solution.java b/_includes/_root/combination-sum-ii/Solution.java deleted file mode 100644 index c3b2627..0000000 --- a/_includes/_root/combination-sum-ii/Solution.java +++ /dev/null @@ -1,63 +0,0 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - HashSet block; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - String uid = found.toString(); - - if(!block.contains(uid)){ - rt.add(found); - block.add(uid); - } - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target && i <= 1; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - public List> combinationSum2(int[] num, int target) { - Arrays.sort(num); - - candidates = num; - this.target = target; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - block = new HashSet(); - - search(0, 0); - - return rt; - - } -} diff --git a/_includes/_root/combination-sum/README.md b/_includes/_root/combination-sum/README.md deleted file mode 100644 index a731d0e..0000000 --- a/_includes/_root/combination-sum/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Apply DFS pattern - -See DFS pattern in [N-Queens](../n-queens) - - - * `steps`: choose a candidate number - * `choices each step`: 0..INFINITE times candidate number - * `possibility checker`: sum of current numbers is less than or equals to target number - -### Backtracking - -Remove the selected candidate number from steps. diff --git a/_includes/_root/combination-sum/Solution.java b/_includes/_root/combination-sum/Solution.java deleted file mode 100644 index 7bb1278..0000000 --- a/_includes/_root/combination-sum/Solution.java +++ /dev/null @@ -1,56 +0,0 @@ -public class Solution { - int target; - - int[] candidates; - - int[] stack; - - ArrayList> rt; - - void search(int sp, int cur){ - - if(cur == target){ - ArrayList found = new ArrayList(); - for(int i = 0; i < stack.length; i++){ - for(int j = 0; j < stack[i]; j++){ - found.add(candidates[i]); - } - } - - rt.add(found); - return; - - } - - if(sp >= stack.length){ - return; - } - - int toadd = candidates[sp]; - - for(int i = 0; cur + toadd * i <= target; i++ ){ - stack[sp] = i; - search(sp + 1, cur + toadd * i); - stack[sp] = 0; - } - - } - - - public List> combinationSum(int[] candidates, int target) { - Arrays.sort(candidates); - - this.target = target; - - this.candidates = candidates; - - stack = new int[candidates.length]; - - rt = new ArrayList>(); - - search(0, 0); - - return rt; - - } -} diff --git a/_includes/_root/combinations/README.md b/_includes/_root/combinations/README.md deleted file mode 100644 index 2739c36..0000000 --- a/_includes/_root/combinations/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Apply DFS pattern - -See DFS pattern in [N-Queens](../n-queens) - - * `steps`: k nums - * `choices each step`: all other numbers from 1 .. n - * `possibility checker`: next number must be greater than all selected numbers - -An easy DFS problem. diff --git a/_includes/_root/combinations/Solution.java b/_includes/_root/combinations/Solution.java deleted file mode 100644 index 83fdc3c..0000000 --- a/_includes/_root/combinations/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -public class Solution { - - Integer[] num; - Integer[] stack; - int target; - - ArrayList> found; - - - void search(int p){ - if(p == target){ - found.add(new ArrayList(Arrays.asList(stack))); - return; - } - - for(Integer n : num){ - if(p > 0 && n <= stack[p - 1]) continue; - - stack[p] = n; - search(p + 1); - } - } - - public List> combine(int n, int k) { - - target = k; - - num = new Integer[n]; - for(int i = 1; i <= n; i++) num[i - 1] = i; - - stack = new Integer[k]; - - found = new ArrayList>(); - - search(0); - - return found; - } -} diff --git a/_includes/_root/compare-version-numbers/README.md b/_includes/_root/compare-version-numbers/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/compare-version-numbers/Solution.java b/_includes/_root/compare-version-numbers/Solution.java deleted file mode 100644 index 19d3360..0000000 --- a/_includes/_root/compare-version-numbers/Solution.java +++ /dev/null @@ -1,48 +0,0 @@ -public class Solution { - - String padding(String s, int len){ - if(s == null) s = ""; - - char[] p = new char[len - s.length()]; - - Arrays.fill(p, '0'); - - return new String(p) + s; - } - - int len(String s){ - if(s == null) return 0; - return s.length(); - } - - public int compareVersion(String version1, String version2) { - String[] v1 = version1.split("\\."); - String[] v2 = version2.split("\\."); - - int m = Math.max(v1.length, v2.length); - - v1 = Arrays.copyOf(v1, m); - v2 = Arrays.copyOf(v2, m); - - for(int i = 0; i < m; i++){ - String s1 = v1[i]; - String s2 = v2[i]; - - int l = Math.max(len(s1), len(s2)); - - s1 = padding(s1, l); - s2 = padding(s2, l); - - for(int j = 0; j < l; j++){ - if(s1.charAt(j) > s2.charAt(j)){ - return 1; - }else if(s1.charAt(j) < s2.charAt(j)){ - return -1; - } - } - - } - - return 0; - } -} diff --git a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/README.md b/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/README.md deleted file mode 100644 index 8397cd7..0000000 --- a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Same as [Construct Binary Tree from Preorder and Inorder Traversal](../construct-binary-tree-from-preorder-and-inorder-traversal) - -The difference is run from end to 0 instead of run from 0 to end. - -In additional, we should contruct the right tree before the left one. - -``` -Pre-order: A, C, E, D, B, H, I, G, F - <- p - -In-order: A, B, C, D, E, F, G, H, I - q - -``` diff --git a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java b/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java deleted file mode 100644 index 0bdc2db..0000000 --- a/_includes/_root/construct-binary-tree-from-inorder-and-postorder-traversal/Solution.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int[] inorder; - int[] postorder; - int p; - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; - - TreeNode root = new TreeNode(postorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != postorder[p] ; i++); - - p--; - root.right = buildTree(i + 1, ed); - root.left = buildTree(st, i); - - return root; - } - - public TreeNode buildTree(int[] inorder, int[] postorder) { - - this.p = postorder.length - 1; - this.inorder = inorder; - this.postorder = postorder; - - return buildTree(0, inorder.length); - } -} \ No newline at end of file diff --git a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/README.md b/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/README.md deleted file mode 100644 index b58b628..0000000 --- a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Recursion - -``` -Pre-order: F, B, A, D, C, E, G, I, H - p - -In-order: A, B, C, D, E, F, G, H, I - q - -``` - -From first char `F` in `Pre-order`, we are sure that the root of the tree is `F`. - -and from `In-order`, `F` divide the tree into two parts, the left one is `A, B, C, D, E`, the right one is `G, H, I`. - -``` - F - / \ -A, B, C, D, E G, H, I - -``` - -`A, B, C, D, E` and `B, A, D, C, E` become a new `buildTree` problem. so we can build the tree recursively. -the result tree is the left children of `F`. - - -Similarly, `G, H, I` and `G, I, H` become the right children of `F`. diff --git a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java b/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java deleted file mode 100644 index ead52a6..0000000 --- a/_includes/_root/construct-binary-tree-from-preorder-and-inorder-traversal/Solution.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int p = 0; - int[] preorder; - int[] inorder; - - - TreeNode buildTree(int st, int ed){ - - if(st >= ed) return null; // - - TreeNode root = new TreeNode(preorder[p]); - - int i; - for(i = st ; i< ed && inorder[i] != preorder[p] ; i++); - - p++; - root.left = buildTree(st, i); - root.right = buildTree(i + 1, ed); - - return root; - } - - - public TreeNode buildTree(int[] preorder, int[] inorder) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - this.preorder = preorder; - this.inorder = inorder; - this.p = 0; - //if (preorder.length == 0) return null; - return buildTree(0 , inorder.length); - //return new TreeNode(preorder[p]); - } -} \ No newline at end of file diff --git a/_includes/_root/container-with-most-water/README.md b/_includes/_root/container-with-most-water/README.md deleted file mode 100644 index 797d58d..0000000 --- a/_includes/_root/container-with-most-water/README.md +++ /dev/null @@ -1,122 +0,0 @@ -## Container's area - -`area = heigt * width` - -A container in this problem has two heights. According to [Liebig's law of the minimum](http://en.wikipedia.org/wiki/Liebig's_law_of_the_minimum), -the smaller height should be selected to calculate the area. - - - -``` -i and j is the index of the input - -function area(i, j) - return MIN(height[i], height[j]) * ABS(i - j) - -``` - -## Maximizing the area - -Maybe, sometimes, I'd to brute force every pair of `i` and `j`. - -``` -max = MIN_VALUE - -foreach i in heights - foreach j in heights - - max = MAX(area(i,j), max) -``` - -### Using brain - -#### Needless comparing - -Instead of brute force each `i` and `j`, we can choose the next `i` or `j` which may cause the area bigger. - -take a look at `MIN(height[i], height[j]) * ABS(i - j)`, when the enumeration is like - - -``` -foreach i = 0 -> end - foreach j = end -> 0 - - max = MAX(area(i,j), max) -``` - -the `i` and `j` are getting closer, so the only factor is `MIN(height[i], height[j])`. -Attempting to compare the `height`s smaller than `MIN(height[i], height[j])` are needless. - - -#### Redundant enumeration - -After `i` and `j` meet each other, the rest of enumeration are redundant. so improved version should be like - - -``` -foreach i = 0 -> end - foreach j = end -> i - - max = MAX(area(i,j), max) -``` - -now, lets see what happens when `i` moves to `i + 1` and `j` remains the same. - - -``` -height[i] > height[j] and height[i + 1] < height[j] - MIN(height[i], height[j]) = height[j] - MIN(height[i + 1], height[j]) = height[i + 1] - - area's height is getting smaller - - -height[i] > height[j] and height[i + 1] > height[j] - MIN(height[i], height[j]) = height[j] - MIN(height[i + 1], height[j]) = height[j] - - area's height remains the same - - -height[i] < height[j] and height[i + 1] < height[j] - MIN(height[i], height[j]) = height[i] - MIN(height[i + 1], height[j]) = MIN(height[i], height[i + 1]) - - area's height is getting smaller - - -height[i] < height[j] and height[i + 1] > height[j] - MIN(height[i], height[j]) = height[i] - MIN(height[i + 1], height[j]) = height[j] - - area's height is getting bigger - -``` - -as you can see only `height[i] < height[j]`, then `i` moves to `i + 1` might generate a bigger area. -this also applies to `j` moves to `j - 1`. - -Now, our greedy code goes as following - - -``` -i = 0 -j = end - -while i and j not meet - - max = MAX(area(i,j), max) - - if height[i] < height[j] - i = i + 1 - - if height[i] > height[j] - j = j - 1 - -``` - - - - - - diff --git a/_includes/_root/container-with-most-water/Solution.java b/_includes/_root/container-with-most-water/Solution.java deleted file mode 100644 index f697152..0000000 --- a/_includes/_root/container-with-most-water/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -public class Solution { - public int maxArea(int[] height) { - - if(height.length <= 1) return 0; - - - int st = 0; - int ed = height.length - 1; - - - int max = Integer.MIN_VALUE; - - while(st < ed){ - - int current = Math.min(height[st] , height[ed]) * (ed - st); - - if(current > max) max = current; - - if(height[st] <= height[ed]){ - st++; - }else{ - ed--; - } - - - } - - - return max; - - } -} \ No newline at end of file diff --git a/_includes/_root/convert-sorted-array-to-binary-search-tree/README.md b/_includes/_root/convert-sorted-array-to-binary-search-tree/README.md deleted file mode 100644 index 2b21ae9..0000000 --- a/_includes/_root/convert-sorted-array-to-binary-search-tree/README.md +++ /dev/null @@ -1,18 +0,0 @@ -## Height balanced BST - -If `balanced` is not required, we can add all number to the right node one by one. - -`BST` and `QuickSort` are good friends. The pivot here is the middle of the input array. - -code looks like `QuickSort`, too. - -``` -function sortedArrayToBST(array) - - root = middle of array - - root.left = sortedArrayToBST(number on the root's left) - root.right = sortedArrayToBST(number on the root's right) - - -``` diff --git a/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java b/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java deleted file mode 100644 index 7c899fa..0000000 --- a/_includes/_root/convert-sorted-array-to-binary-search-tree/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - //TreeNode - - public TreeNode sortedArrayToBST(int[] num) { - - if(num.length == 0) - return null; - - if(num.length == 1) - return new TreeNode(num[0]); - - int mid = num.length / 2; - - TreeNode root = new TreeNode(num[mid]); - - root.left = sortedArrayToBST(Arrays.copyOfRange(num, 0, mid)); - root.right = sortedArrayToBST(Arrays.copyOfRange(num, mid + 1, num.length)); - - return root; - - } -} \ No newline at end of file diff --git a/_includes/_root/convert-sorted-list-to-binary-search-tree/README.md b/_includes/_root/convert-sorted-list-to-binary-search-tree/README.md deleted file mode 100644 index 4694fd8..0000000 --- a/_includes/_root/convert-sorted-list-to-binary-search-tree/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Linked list version of [Convert Sorted Array to Binary Search Tree](../convert-sorted-array-to-binary-search-tree) - -Linked list version is a litte more difficult, we have to find the `mid` of a linked list. - -Fast-slow pointer is a good tool for find `mid` of a linked list. see [Reorder List](reorder-list) diff --git a/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java b/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java deleted file mode 100644 index ded690f..0000000 --- a/_includes/_root/convert-sorted-list-to-binary-search-tree/Solution.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; next = null; } - * } - */ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - ListNode cutatmid(ListNode head){ - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - ListNode pslow = head; - - while(fast != null && fast.next != null){ - pslow = slow; - slow = slow.next; - fast = fast.next.next; - } - - pslow.next = null; - return slow; - } - - public TreeNode sortedListToBST(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - if(head.next == null) return new TreeNode(head.val); - - ListNode mid = cutatmid(head); - - TreeNode root = new TreeNode(mid.val); - root.left = sortedListToBST(head); - root.right = sortedListToBST(mid.next); - - return root; - } -} \ No newline at end of file diff --git a/_includes/_root/copy-list-with-random-pointer/README.md b/_includes/_root/copy-list-with-random-pointer/README.md deleted file mode 100644 index ee52e6d..0000000 --- a/_includes/_root/copy-list-with-random-pointer/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Same as [Clone Graph](../clone-graph) - -even same code structure... diff --git a/_includes/_root/copy-list-with-random-pointer/Solution.java b/_includes/_root/copy-list-with-random-pointer/Solution.java deleted file mode 100644 index 947fd8d..0000000 --- a/_includes/_root/copy-list-with-random-pointer/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for singly-linked list with a random pointer. - * class RandomListNode { - * int label; - * RandomListNode next, random; - * RandomListNode(int x) { this.label = x; } - * }; - */ -public class Solution { - public RandomListNode copyRandomList(RandomListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - HashMap map = new HashMap(); - - RandomListNode iter = head; - while(iter != null){ - RandomListNode born = new RandomListNode(iter.label); - map.put(iter, born); - - iter = iter.next; - } - - iter = head; - - while(iter != null){ - RandomListNode islet = map.get(iter); - - islet.next = map.get(iter.next); - islet.random = map.get(iter.random); - - iter = iter.next; - } - - return map.get(head); - } -} \ No newline at end of file diff --git a/_includes/_root/count-and-say/README.md b/_includes/_root/count-and-say/README.md deleted file mode 100644 index 688224e..0000000 --- a/_includes/_root/count-and-say/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Just do as what the problem asks you to do - - - 1. init string `1` - 1. count - 1. say - 1. loop `n` times - diff --git a/_includes/_root/count-and-say/Solution.java b/_includes/_root/count-and-say/Solution.java deleted file mode 100644 index d8c902a..0000000 --- a/_includes/_root/count-and-say/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -public class Solution { - - String countAndSay(String prev){ - - char[] str = prev.toCharArray(); - - int p = 1; - int count = 1; - char last = str[0]; - - String s = ""; - - while(p < str.length){ - - if(str[p] == last){ - count++; - - }else{ - - s += "" + count + last; - - last = str[p]; - count = 1; - } - - p++; - } - - s += "" + count + last; - - return s; - } - - public String countAndSay(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - String init = "1"; - - for(int i = 0; i < n - 1; i++){ - init = countAndSay(init); - } - - return init; - - } -} \ No newline at end of file diff --git a/_includes/_root/decode-ways/README.md b/_includes/_root/decode-ways/README.md deleted file mode 100644 index c1fc7ea..0000000 --- a/_includes/_root/decode-ways/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Jump 1 or 2 steps, [Climbing Stairs](../climbing-stairs) - -"12", it could be decoded as "AB" (1 2) or "L" (12). - -It is just like jumping 1 step A B or 2 steps 12. - -But, there are some restrictions. - -e.g. - -"31" can only decode as "C" (3) and "A" (1) - -So, what we need to do is to add something to the `Climbing Stairs`, do not climb the invalid stairs. diff --git a/_includes/_root/decode-ways/Solution.java b/_includes/_root/decode-ways/Solution.java deleted file mode 100644 index ea87fa8..0000000 --- a/_includes/_root/decode-ways/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -public class Solution { - - public int numDecodings(String s) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - final char[] _s = s.toCharArray(); - final int n = _s.length; - - if (n == 0 ) return 0; - - int[] step = new int[Math.max(n + 1, 3)]; - - step[0] = 1; - - step[1] = 0; - - if(_s[0] != '0') - step[1] = 1; - - for(int i = 2; i <= n; i++){ - - step[i] = 0; - - if ( _s[i - 1] != '0' ){ - step[i] += step[i - 1]; - } - - if ( _s[i - 2] != '0' ){ - if ( (_s[i - 2] - '0') * 10 + (_s[i - 1] - '0') <= 26 ) - step[i] += step[i - 2]; - } - - } - - return step[n]; - } - -} \ No newline at end of file diff --git a/_includes/_root/distinct-subsequences/README.md b/_includes/_root/distinct-subsequences/README.md deleted file mode 100644 index 9256e48..0000000 --- a/_includes/_root/distinct-subsequences/README.md +++ /dev/null @@ -1,194 +0,0 @@ -## Guessing - -Lets start with `rabbbit` and `rabbit`. - -To make the problem easier, start from one char, `distinct subsequences` of `rabbbit` and `r`. - -`distinct subsequences` below, by eyeball: - - * `r` and `r` has 1 `distinct subsequences` - * `a` and `r` has 0 `distinct subsequences` - -These two are easy to be understood. - - * `ra` and `r` has 1 `distinct subsequences` - * `rab` and `r` has 1 `distinct subsequences` - * `rabbbbbbbbbbbb` and `r` has 1 `distinct subsequences` - -These three show that `r` plus any junk chars will not change `distinct subsequences` - - * `rr` and `r` has 2 `distinct subsequences` - * `rar` and `r` has 2 `distinct subsequences` - * `rara` and `r` has 2 `distinct subsequences` - * `rarar` and `r` has 3 `distinct subsequences` - -`rar` and `r` is same as `rr` and `r`, because `a` there has nothing to do with the number of `distinct subsequences`, it is a junk like above. - -In another word, `rar` and `r` can be converted to `ra` + `r` and `r`, that is `1 + 1`. - -### Put them into table - -the value `P[i][j]` means that `S[0..i]` and `T[0..j]` has `P[i][j]` `distinct subsequences`. - -the table with only one char - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -``` - -Enlarge the table - - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| a | | | | | | | | -+---+---+---+---+---+---+---+---+ -| b | | | | | | | | -+---+---+---+---+---+---+---+---+ -| b | | | | | | | | -+---+---+---+---+---+---+---+---+ -| i | | | | | | | | -+---+---+---+---+---+---+---+---+ -| t | | | | | | | | -+---+---+---+---+---+---+---+---+ -``` - -Some grids here are easy to be filled, the grids which `j > i`. -That is, T is longer than S, there will be no `distinct subsequences`. - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| a | 0 | | | | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | | | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 0 | | | | | -+---+---+---+---+---+---+---+---+ -| i | 0 | 0 | 0 | 0 | | | | -+---+---+---+---+---+---+---+---+ -| t | 0 | 0 | 0 | 0 | 0 | | | -+---+---+---+---+---+---+---+---+ -``` - -`j == i` grids are easy too, the S and T must be the same if it wants to have 1 `distinct subsequences`. - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| a | 0 | 1 | | | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 1 | | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 0 | 1 | | | | -+---+---+---+---+---+---+---+---+ -| i | 0 | 0 | 0 | 0 | 0 | | | -+---+---+---+---+---+---+---+---+ -| t | 0 | 0 | 0 | 0 | 0 | 0 | | -+---+---+---+---+---+---+---+---+ -``` - -This pictrue is just encouraging you, as there is only a few grids left to be filled. - -### `rab` and `ra` - -This problem looks familiar. It is the `ra` and `r`. - -as `b` is a junk char, `rab` should have the same number as `ra` and `ra`. - -Then the table is like - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| a | 0 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 1 | | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 0 | 1 | | | | -+---+---+---+---+---+---+---+---+ -| i | 0 | 0 | 0 | 0 | 0 | | | -+---+---+---+---+---+---+---+---+ -| t | 0 | 0 | 0 | 0 | 0 | 0 | | -+---+---+---+---+---+---+---+---+ -``` - -### `rabb` and `rab` - -This time, add a new `b` to both `rab` and `ra`. - -#### Use the new `b` in subsequences - -This time they have same letter, `b` , at the end. It is not a junk. - -This time, remove `b` from both S and T, then they become `rab` and `ra`. - -that is, this will take `rab` and `ra` `distinct subsequences`. - -#### Dont use the new `b` - -Treat `b` as junk, it has `rab` and `rab` `distinct subsequences`. - - -#### Sum up two choices - -Use or not will result two set of `distinct subsequences`, so sum them up. - -`rabb` and `rab` = `rab` and `ra` + `rab` and `rab`. - -``` -+---+---+---+---+---+---+---+---+ -| | r | a | b | b | b | i | t | -+---+---+---+---+---+---+---+---+ -| r | 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| a | 0 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 1 | 2 | | | | -+---+---+---+---+---+---+---+---+ -| b | 0 | 0 | 0 | 1 | | | | -+---+---+---+---+---+---+---+---+ -| i | 0 | 0 | 0 | 0 | 0 | | | -+---+---+---+---+---+---+---+---+ -| t | 0 | 0 | 0 | 0 | 0 | 0 | | -+---+---+---+---+---+---+---+---+ -``` - -## General form - -the grid `P[i][j]` has 1 choice when `S[i] != T[j]`, this only adds some junk chars. - -``` -P[i][j] = P[i - 1][j] -``` - -the grid `P[i][j]` has 2 choice when `S[i] == T[j]` - -``` -P[i][j] = -P[i - 1][j] // adds as junk chars. -+ -P[i - 1][j - 1] // use the new char in the new subsequence - -``` - -Fill up the table and the bottom right grid is the answer. - - diff --git a/_includes/_root/distinct-subsequences/Solution.java b/_includes/_root/distinct-subsequences/Solution.java deleted file mode 100644 index 54077ac..0000000 --- a/_includes/_root/distinct-subsequences/Solution.java +++ /dev/null @@ -1,50 +0,0 @@ -public class Solution { - public int numDistinct(String S, String T) { - - - char[] s = S.toCharArray(); - if(s.length == 0) return 0; - - char[] t = T.toCharArray(); - if(t.length == 0) return 0; - - if(t.length > s.length) return 0; - - - int[][] P = new int[s.length][t.length]; - - - P[0][0] = s[0] == t[0] ? 1 : 0; - - for(int i = 1; i < s.length; i++){ - P[i][0] = s[i] == t[0] ? 1 + P[i - 1][0] : P[i - 1][0]; - } - - - for(int j = 1; j < t.length; j++){ - for(int i = j; i < s.length; i++){ - - if(t[j] == s[i]){ - // sum choices - - P[i][j] = P[i - 1][j] + P[i - 1][j - 1]; - - - } else { - // no choice - P[i][j] = P[i - 1][j]; - - } - - - - - } - } - - - return P[s.length - 1][t.length - 1]; - - - } -} \ No newline at end of file diff --git a/_includes/_root/divide-two-integers/README.md b/_includes/_root/divide-two-integers/README.md deleted file mode 100644 index 32b7ae6..0000000 --- a/_includes/_root/divide-two-integers/README.md +++ /dev/null @@ -1,36 +0,0 @@ -## Simulting via Minus - - -``` -while dividend >= divisor - dividend = dividend - divisor - quotient = quotient + 1 - -``` - -## Accelerating - -Above code will exceed time limit. -We can remove a bit more `divisor`s from `dividend`. - - -``` -acceleration = 1 -cached_accelerated_divisor = divisor - -while dividend >= divisor - - if cached_accelerated_divisor > dividend - // slow down - acceleration = acceleration - 1 - cached_accelerated_divisor = cached_accelerated_divisor - divisor - else - - dividend = dividend - cached_accelerated_divisor - quotient = quotient + acceleration -``` - - -## Overflow - -leetcode's testcases covered some edge case like `Integer.MIN_VALUE` and `Integer.MAX_VALUE`, take care. diff --git a/_includes/_root/divide-two-integers/Solution.java b/_includes/_root/divide-two-integers/Solution.java deleted file mode 100644 index 8ca078a..0000000 --- a/_includes/_root/divide-two-integers/Solution.java +++ /dev/null @@ -1,43 +0,0 @@ -public class Solution { - public int divide(int dividend, int divisor) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(dividend == 0) return 0; - - if(dividend == Integer.MIN_VALUE){ - if(divisor < 0) - return 1 + divide(dividend - divisor, divisor); - else - return 0 - (1 + 0 - divide((dividend + divisor), divisor)); - } - - if(divisor == Integer.MIN_VALUE){ - return dividend == divisor ? 1 : 0; - } - - if(dividend > 0 && divisor < 0) return 0 - divide(dividend, 0 - divisor); - if(dividend < 0 && divisor > 0) return 0 - divide(0 - dividend, divisor); - if(dividend < 0 && divisor < 0) return divide(0 - dividend, 0 - divisor); - - int quotient = 0; - int a = 1; - - int r = divisor; - - while(dividend >= divisor ){ - - if(r > dividend){ - a--; - r -= divisor; - }else{ - dividend -= r; - quotient += a++; - r += divisor; - } - } - - - - return quotient; - } -} diff --git a/_includes/_root/dungeon-game/README.md b/_includes/_root/dungeon-game/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/dungeon-game/Solution.java b/_includes/_root/dungeon-game/Solution.java deleted file mode 100644 index 689cb88..0000000 --- a/_includes/_root/dungeon-game/Solution.java +++ /dev/null @@ -1,37 +0,0 @@ -public class Solution { - - int minHealthReach(int hp, int room){ - hp -= room; - if(hp <= 0){ - return 1; - } - - return hp; - } - - public int calculateMinimumHP(int[][] dungeon) { - - final int mx = dungeon.length; - final int my = dungeon[0].length; - - dungeon[mx - 1][my - 1] = minHealthReach(1, dungeon[mx - 1][my - 1]); - - for(int i = mx - 2; i >= 0; i--){ - dungeon[i][my - 1] = minHealthReach(dungeon[i + 1][my - 1], dungeon[i][my - 1]); - } - - for(int j = my - 2; j >= 0; j--){ - dungeon[mx - 1][j] = minHealthReach(dungeon[mx - 1][j + 1], dungeon[mx - 1][j]); - } - - - for(int i = mx - 2; i >= 0; i--){ - for(int j = my - 2; j >= 0; j--){ - dungeon[i][j] = minHealthReach(Math.min(dungeon[i + 1][j], dungeon[i][j + 1]), dungeon[i][j]); - } - } - - return dungeon[0][0]; - - } -} diff --git a/_includes/_root/edit-distance/README.md b/_includes/_root/edit-distance/README.md deleted file mode 100644 index 13bbf9f..0000000 --- a/_includes/_root/edit-distance/README.md +++ /dev/null @@ -1,164 +0,0 @@ -## [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) - -This is a well known problem. - - -Illustrating this problem using wikipedia's example - -Making a table like [Interleaving String](../interleaving-string) - -``` -+---+---+---+---+---+---+---+---+ -| | * | k | i | t | t | e | n | -+---+---+---+---+---+---+---+---+ -| * | | | | | | | | -+---+---+---+---+---+---+---+---+ -| s | | | | | | | | -+---+---+---+---+---+---+---+---+ -| i | | | | | | | | -+---+---+---+---+---+---+---+---+ -| t | | | | | | | | -+---+---+---+---+---+---+---+---+ -| t | | | | | | | | -+---+---+---+---+---+---+---+---+ -| i | | | | | | | | -+---+---+---+---+---+---+---+---+ -| n | | | | | | | | -+---+---+---+---+---+---+---+---+ -| g | | | | | | | | -+---+---+---+---+---+---+---+---+ - -``` - -`*` here is representing an empty string - -each gird is the `edit distance` of `string[0..x]` and `string[0..y]` - -First row and column girds are easy to be filled: - - * `edit distance` of an empty string to an empty string is `0` - * `edit distance` of an empty string to any string is the length of that string - -So the table should be filled like: - -``` -+---+---+---+---+---+---+---+---+ -| | * | k | i | t | t | e | n | -+---+---+---+---+---+---+---+---+ -| * | 0 | 1 | 2 | 3 | 4 | 5 | 6 | -+---+---+---+---+---+---+---+---+ -| s | 1 | | | | | | | -+---+---+---+---+---+---+---+---+ -| i | 2 | | | | | | | -+---+---+---+---+---+---+---+---+ -| t | 3 | | | | | | | -+---+---+---+---+---+---+---+---+ -| t | 4 | | | | | | | -+---+---+---+---+---+---+---+---+ -| i | 5 | | | | | | | -+---+---+---+---+---+---+---+---+ -| n | 6 | | | | | | | -+---+---+---+---+---+---+---+---+ -| g | 7 | | | | | | | -+---+---+---+---+---+---+---+---+ - -``` - -### what's about `k` and `s` - -in `k`'s view - - * Insert: cant transform to `s` - * Delete: cant transform to `s` - * Replace: replace `k` to `s` use `1` `edit distance` - -in `s`'s view - - * Insert: cant transform to `k` - * Delete: cant transform to `k` - * Replace: replace `s` to `k` use `1` `edit distance` - -so the number in the gird `k` and `s` should be `1` - -### what's about `ki` and `s` (in `ki`'s view) - - * Insert: cant transform to `s` - * Delete: delete `i` then, transform to the problem `s` and `k` we solved before. 1 + `edit distance` of `s` and `k`. - * Replace and Delete: replace `k` to `s` use `1` `edit distance`, then delete `k` use `1` `edit distance`. `1 + 1 = 2` - - -`Delete` and `Replace then Delete` are the same thing at last, `Replace` is just the `1` `edit distance` costed by `edit distance` of `s` and `k`. - -In this case, we can transform the problem by deleting one char: 1 + `edit distance` of `string deleted one` and `k` - -We can fill up the second column and row now: - - -``` -+---+---+---+---+---+---+---+---+ -| | * | k | i | t | t | e | n | -+---+---+---+---+---+---+---+---+ -| * | 0 | 1 | 2 | 3 | 4 | 5 | 6 | -+---+---+---+---+---+---+---+---+ -| s | 1 | 1 | 2 | 3 | 4 | 5 | 6 | -+---+---+---+---+---+---+---+---+ -| i | 2 | 2 | | | | | | -+---+---+---+---+---+---+---+---+ -| t | 3 | 3 | | | | | | -+---+---+---+---+---+---+---+---+ -| t | 4 | 4 | | | | | | -+---+---+---+---+---+---+---+---+ -| i | 5 | 5 | | | | | | -+---+---+---+---+---+---+---+---+ -| n | 6 | 6 | | | | | | -+---+---+---+---+---+---+---+---+ -| g | 7 | 7 | | | | | | -+---+---+---+---+---+---+---+---+ - -``` - -### What if `si` and `ki` - -Obviously, `si` and `ki` equals to the `edit distance` of `s` and `k`, because `i` are both in two strings. - -``` -+---+---+---+---+---+---+---+---+ -| | * | k | i | t | t | e | n | -+---+---+---+---+---+---+---+---+ -| * | 0 | 1 | 2 | 3 | 4 | 5 | 6 | -+---+---+---+---+---+---+---+---+ -| s | 1 | 1 | 2 | 3 | 4 | 5 | 6 | -+---+---+---+---+---+---+---+---+ -| i | 2 | 2 | 1 | | | | | -+---+---+---+---+---+---+---+---+ -| t | 3 | 3 | | | | | | -+---+---+---+---+---+---+---+---+ -| t | 4 | 4 | | | | | | -+---+---+---+---+---+---+---+---+ -| i | 5 | 5 | | | | | | -+---+---+---+---+---+---+---+---+ -| n | 6 | 6 | | | | | | -+---+---+---+---+---+---+---+---+ -| g | 7 | 7 | | | | | | -+---+---+---+---+---+---+---+---+ - -``` - -then we can fill up the table using technology we used before. - - -### More common case - -`P[word1][word2]` is the the table, - -so `P[i][j]` have 4 choices: - - * `P[i - 1][j] + 1` : by deleting `word1[i]` from `word1` and convert to previous problem. - * `P[i][j - 1] + 1` : by deleting `word2[j]` from `word2` and convert to previous problem. - * `P[i - 1][j - 1]` : only if `word1[i] == word2[j]` - * `P[i - 1][j - 1] + 1` : only if `word1[i] != word2[j]`, then replace one char `word1[i]` to `word2[j]`, then this problem is converted to `P[i - 1][j - 1]`. - -Dont worry about `Insertion`, it is just the oppsite to `Deletion`. Just different view. - - -So the work remaing is easy, find the MIN of those four is ok. diff --git a/_includes/_root/edit-distance/Solution.java b/_includes/_root/edit-distance/Solution.java deleted file mode 100644 index 97d9d43..0000000 --- a/_includes/_root/edit-distance/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -public class Solution { - public int minDistance(String word1, String word2) { - - // http://en.wikipedia.org/wiki/Levenshtein_distance - - char[] w1 = word1.toCharArray(); - char[] w2 = word2.toCharArray(); - - - - int[][] P = new int[w1.length + 1][w2.length + 1]; - - int i, j; - - for(i = 1; i <= w1.length; i++){ - P[i][0] = i; - } - - for(j = 1; j <= w2.length; j++){ - P[0][j] = j; - } - - for(i = 1; i <= w1.length; i++){ - for(j = 1; j <= w2.length; j++){ - - P[i][j] = Math.min(P[i - 1][j], P[i][j - 1]) + 1; - - if(w1[i - 1] == w2[j - 1]){ - P[i][j] = Math.min(P[i - 1][j - 1], P[i][j]); - }else { - P[i][j] = Math.min(P[i - 1][j - 1] + 1, P[i][j]); - } - - } - } - - return P[w1.length][w2.length]; - } -} \ No newline at end of file diff --git a/_includes/_root/evaluate-reverse-polish-notation/README.md b/_includes/_root/evaluate-reverse-polish-notation/README.md deleted file mode 100644 index 0adac06..0000000 --- a/_includes/_root/evaluate-reverse-polish-notation/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) - -classic case of stack. - - 1. pop two number from stack and calculate if current token is a notation - 1. push to stack if current token is number diff --git a/_includes/_root/evaluate-reverse-polish-notation/Solution.java b/_includes/_root/evaluate-reverse-polish-notation/Solution.java deleted file mode 100644 index e148b49..0000000 --- a/_includes/_root/evaluate-reverse-polish-notation/Solution.java +++ /dev/null @@ -1,35 +0,0 @@ -public class Solution { - public int evalRPN(String[] tokens) { - - final Deque stack = new LinkedList(); - - for(String t : tokens){ - if("+".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 + v2); - }else if("-".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 - v2); - }else if("*".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 * v2); - }else if("/".equals(t)){ - Integer v2 = stack.pop(); - Integer v1 = stack.pop(); - - stack.push(v1 / v2); - }else{ - stack.push(Integer.valueOf(t)); - } - } - - return stack.pop(); - - } -} diff --git a/_includes/_root/excel-sheet-column-number/README.md b/_includes/_root/excel-sheet-column-number/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/excel-sheet-column-number/Solution.java b/_includes/_root/excel-sheet-column-number/Solution.java deleted file mode 100644 index befc36d..0000000 --- a/_includes/_root/excel-sheet-column-number/Solution.java +++ /dev/null @@ -1,18 +0,0 @@ -public class Solution { - public int titleToNumber(String s) { - char[] S = s.toCharArray(); - - int n = 0; - - int p = 1; - - for(int i = S.length - 1; i >= 0; i--){ - - n += (S[i] - 'A' + 1) * p; - - p *= 26; - } - - return n; - } -} diff --git a/_includes/_root/excel-sheet-column-title/README.md b/_includes/_root/excel-sheet-column-title/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/excel-sheet-column-title/Solution.java b/_includes/_root/excel-sheet-column-title/Solution.java deleted file mode 100644 index c958d8f..0000000 --- a/_includes/_root/excel-sheet-column-title/Solution.java +++ /dev/null @@ -1,13 +0,0 @@ -public class Solution { - public String convertToTitle(int n) { - if(n < 27){ - return (char)('A' + (n - 1)) + ""; - } - - if( n % 26 == 0) { - return convertToTitle(n / 26 - 1) + 'Z'; - } - - return convertToTitle(n / 26) + convertToTitle(n % 26); - } -} diff --git a/_includes/_root/factorial-trailing-zeroes/README.md b/_includes/_root/factorial-trailing-zeroes/README.md deleted file mode 100644 index 3f5e2b3..0000000 --- a/_includes/_root/factorial-trailing-zeroes/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## A trailing zero is made of factor 2 and factor 5 - -``` -n! = 2 ^ m * 5 ^ n * (other factors) -``` - -the count of trailing zero is `min(m, n)`. -because a `2` and a `5` generates a zero. - - -the work is just counting 2 and 5 ... diff --git a/_includes/_root/factorial-trailing-zeroes/Solution.java b/_includes/_root/factorial-trailing-zeroes/Solution.java deleted file mode 100644 index e3c95d5..0000000 --- a/_includes/_root/factorial-trailing-zeroes/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -public class Solution { - public int trailingZeroes(int n) { - - int count = 0; - - int c2 = 0; // count of 2 - int c5 = 0; // count of 5 - - for (int i = 1; i <= n; i++){ - int m = i; - - while(m % 5 == 0){ - m /= 5; - c5++; - } - - while(m % 2 == 0){ - m /= 2; - c2++; - } - - int c = Math.min(c2, c5); - - count += c; - c2 -= c; - c5 -= c; - - } - - return count; - - } -} diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/README.md b/_includes/_root/find-minimum-in-rotated-sorted-array-ii/README.md deleted file mode 100644 index bf96666..0000000 --- a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Merge [Find Minimum in Rotated Sorted Array](../find-minimum-in-rotated-sorted-array) and [Search in Rotated Sorted Array II](../search-in-rotated-sorted-array-ii) - -Patch to [Find Minimum in Rotated Sorted Array](../find-minimum-in-rotated-sorted-array) is -to handle the worst case - -``` -[ 1 1 1 1 1 1 2 1 1 1 1] - s m e -``` - -when `s = m = e` we do not know which part contains the mininum number. -we have to do it in brute force: - -``` -min(num[s], findmin(num[s + 1 .. e])) -``` diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java b/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java deleted file mode 100644 index a43ffe6..0000000 --- a/_includes/_root/find-minimum-in-rotated-sorted-array-ii/Solution.java +++ /dev/null @@ -1,30 +0,0 @@ -public class Solution { - public int findMin(int[] num) { - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // bad case - if (num[s] == num[m] && num[m] == num[e - 1]){ - return Math.min(num[s], findMin(Arrays.copyOfRange(num, s + 1, e))); - } - - // s < m < e - if ( num[s] <= num[m] && num[m] <= num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] <= num[m] && num[m] >= num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - - } -} diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array/README.md b/_includes/_root/find-minimum-in-rotated-sorted-array/README.md deleted file mode 100644 index b8f2af0..0000000 --- a/_includes/_root/find-minimum-in-rotated-sorted-array/README.md +++ /dev/null @@ -1,55 +0,0 @@ -## Variant of [Search in Rotated Sorted Array](../search-in-rotated-sorted-array) - - -### The 3 cases in a `Rotated Sorted Array` when using binary search - - * `s` < `m` < `e` : `min = num[s]` - - - -``` - 1 E - 2 * - 3 * - 4 * - 5 * - 6 M - 7 * - 8 * - 9 * - 10 S -``` - - * `s` < `m` > `e` : min must in `m .. e` - - -``` - 1 * - 2 * - 3 M - 4 * - 5 * - 6 * - 7 S - 8 E - 9 * - 10 * -``` - - * `s` > `m` < `e` min must in `s .. m + 1` - - -``` - 1 * - 2 * - 3 S - 4 E - 5 * - 6 * - 7 * - 8 M - 9 * - 10 * -``` - -Now, Loop until `s` < `m` < `e` diff --git a/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java b/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java deleted file mode 100644 index f5527b2..0000000 --- a/_includes/_root/find-minimum-in-rotated-sorted-array/Solution.java +++ /dev/null @@ -1,25 +0,0 @@ -public class Solution { - public int findMin(int[] num) { - - if(num.length == 1) return num[0]; - if(num.length == 2) return Math.min(num[0], num[1]); - - int s = 0; - int e = num.length; - - int m = (s + e) / 2; - - // s < m < e - if ( num[s] < num[m] && num[m] < num[e - 1]){ - return num[s]; - } - - // s < m > e - if ( num[s] < num[m] && num[m] > num[e - 1]){ - return findMin(Arrays.copyOfRange(num, m, e)); - } - - // s > m < e - return findMin(Arrays.copyOfRange(num, s, m + 1)); - } -} diff --git a/_includes/_root/find-peak-element/README.md b/_includes/_root/find-peak-element/README.md deleted file mode 100644 index e1528e4..0000000 --- a/_includes/_root/find-peak-element/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## logarithmic is a sign - -`O(lg n)` is something like `binary search` or `merge sort`. - - -``` -find-peak-element = first elemen only one element - index_of_max_one (find-peak-element(left half), find-peak-element(right half)) otherwise -``` - - diff --git a/_includes/_root/find-peak-element/Solution.java b/_includes/_root/find-peak-element/Solution.java deleted file mode 100644 index 7dfa2a5..0000000 --- a/_includes/_root/find-peak-element/Solution.java +++ /dev/null @@ -1,18 +0,0 @@ -public class Solution { - - int findPeakElement(int[] num, int from, int to) { - if(to - from == 1) return from; - - int m = (to + from) / 2; - - int l = findPeakElement(num, from, m); - int r = findPeakElement(num, m, to); - - if(num[l] > num[r]) return l; - else return r; - } - - public int findPeakElement(int[] num) { - return findPeakElement(num, 0, num.length); - } -} diff --git a/_includes/_root/first-missing-positive/README.md b/_includes/_root/first-missing-positive/README.md deleted file mode 100644 index 5b4886a..0000000 --- a/_includes/_root/first-missing-positive/README.md +++ /dev/null @@ -1,133 +0,0 @@ -## O(n) time and O(n) space - -if we can use a set, we can put all the input numbers into the set. -and test from 1 to INFINITY, the answer is the first number which is not is the set. - - -``` -set: convert the input array into a set - -foreach i in 1 .. infinity - - if i is not in set - i is the result - -``` - - -## O(1) space - -if we can reuse the input array as the set, we make it O(1) - -a tricky array based set may be like: - -``` -[1, 1, 0, 1, 1, 0, 1] - 1 2 3 4 5 6 7 [index starts from 1] -``` - -from the tricky set, we can see the first missing positive number is `3` - -### Building the set - -``` -[1, 2, 0] -[1, 1, 0] [set] - 1 2 3 [index starts from 1] - -[3, 4, -1, 1] -[1, 0, 1, 1] [set] - 1 2 3 4 [index starts from 1] -``` - -if we can move number in the input set to the `index` position, -we can check if a number in the set by `number == index` - -``` -[1, 2, 0] -[1, 2, 0] [converted array] - 1 2 3 [index starts from 1] - -[3, 4, -1, 1] -[1, -1, 3, 4] [converted array] - 1 2 3 4 [index starts from 1] -``` - -We can build this kind of set by moving the number to the right position. -If number is not a positive number, just leave it there, it may be exchanged in the further. - -#### Building process - - -``` -[3, 4, -1, 1] - 1 2 3 4 [index starts from 1] - - i -``` - - * `3` should be at `index 3`, swap `index i` and `index 3` - -``` -[-1, 4, 3, 1] - 1 2 3 4 [index starts from 1] - - i -``` - - * `-1` should not be in the set, ignore and `i` move to next - -``` -[-1, 4, 3, 1] - 1 2 3 4 [index starts from 1] - - i -``` - - * `4` should be at `index 4`, swap `index i` and `index 4` - -``` -[-1, 1, 3, 4] - 1 2 3 4 [index starts from 1] - - i -``` - - * `1` should be at `index 1`, swap `index i` and `index 1` - -``` -[1, -1, 3, 4] - 1 2 3 4 [index starts from 1] - - i -``` - - * `-1` should not be in the set, ignore and `i` move to next - - -``` -[1, -1, 3, 4] - 1 2 3 4 [index starts from 1] - - i -``` - - * `3` is already at the right position, move `i` to next - -``` -[1, -1, 3, 4] - 1 2 3 4 [index starts from 1] - - i -``` - - * `4` is already at the right position, move `i` to next - - -we can know 2 is the first missing positive number, because `2 != -1`. - - -### Bucket Sort - -This set build process, sometime, is known as Bucket Sort. -In this case we use the input array as the bucket. diff --git a/_includes/_root/first-missing-positive/Solution.java b/_includes/_root/first-missing-positive/Solution.java deleted file mode 100644 index e61e2dc..0000000 --- a/_includes/_root/first-missing-positive/Solution.java +++ /dev/null @@ -1,40 +0,0 @@ -public class Solution { - public int firstMissingPositive(int[] A) { - - final int N = A.length; - - next: - for(int i = 0; i < N; i++){ - int v = A[i]; - - if(v == i + 1) continue ; - - while(true){ - if(v <= 0 || v > N){ - continue next; - } - - int t = A[v - 1]; - - if(t == v){ - continue next; - } - - A[v - 1] = v; - v = t; - } - - } - - for(int i = 0; i < N; i++){ - int v = A[i]; - - if (v != i + 1){ - return i + 1; - } - } - - return N + 1; - - } -} \ No newline at end of file diff --git a/_includes/_root/flatten-binary-tree-to-linked-list/README.md b/_includes/_root/flatten-binary-tree-to-linked-list/README.md deleted file mode 100644 index c366644..0000000 --- a/_includes/_root/flatten-binary-tree-to-linked-list/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Preorder traversal - -Create a linked list from the nodes visited by preorder travelling. diff --git a/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java b/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java deleted file mode 100644 index e1e416c..0000000 --- a/_includes/_root/flatten-binary-tree-to-linked-list/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode prev; - - void preorder(TreeNode root){ - - if(root == null) return; - - TreeNode left = root.left; - TreeNode right = root.right; - - // root - if(prev != null){ - prev.right = root; - prev.left = null; - } - - prev = root; - - preorder(left); - preorder(right); - } - - - public void flatten(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - prev = null; - preorder(root); - } -} \ No newline at end of file diff --git a/_includes/_root/fraction-to-recurring-decimal/README.md b/_includes/_root/fraction-to-recurring-decimal/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/fraction-to-recurring-decimal/Solution.java b/_includes/_root/fraction-to-recurring-decimal/Solution.java deleted file mode 100644 index b845951..0000000 --- a/_includes/_root/fraction-to-recurring-decimal/Solution.java +++ /dev/null @@ -1,55 +0,0 @@ -public class Solution { - - public String fractionToDecimal(int numerator, int denominator) { - - String sign = ""; - - if(Math.signum(numerator) * Math.signum(denominator) < 0){ - sign = "-"; - } - - // cheat ... - long _numerator = numerator; - - long quotient = _numerator / denominator; - - _numerator %= denominator; - _numerator *= 10; - - final String intPart = "" + Math.abs(quotient); - - Map mod = new HashMap(); - - int i = 0; - - StringBuilder sb = new StringBuilder(); - - while(_numerator != 0){ - quotient = Math.abs(_numerator / denominator); - - _numerator %= denominator; - - Integer start = mod.get(_numerator + "," + quotient); - - if(start != null){ - sb.insert(start, "("); - sb.append(")"); - break; - } - - sb.append(quotient); - - mod.put(_numerator + "," + quotient, i); - - _numerator *= 10; - i++; - } - - String fractionalPart = sb.toString(); - - if(!"".equals(fractionalPart)) fractionalPart = "." + fractionalPart; - - return sign + intPart + fractionalPart; - - } -} diff --git a/_includes/_root/gas-station/README.md b/_includes/_root/gas-station/README.md deleted file mode 100644 index 3686eab..0000000 --- a/_includes/_root/gas-station/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Guessing - -This problem is to find a UNIQUE station `i`, such that - - * SUM(gas[0 .. i-1]) - SUM(cost[0 .. i-1]) + SUM(gas[i .. end]) - SUM(cost[i .. end]) >= 0 - * SUM(gas[0 .. i-1]) - SUM(cost[0 .. i-1]) < 0 - -`SUM(gas[0 .. i-1]) - SUM(cost[0 .. i-1]) < 0` is to guarantee that the `i` is unique. - -If `SUM(gas[0 .. i-1]) - SUM(cost[0 .. i-1]) < 0` and `SUM(gas[0 .. i-1]) - SUM(cost[0 .. i-1]) + SUM(gas[i .. end]) - SUM(cost[i .. end]) >= 0`, that is, `0 .. i-1` are all valid stations. - -## Brute force - -Just search through from `0` to `end`, find the valid `i`. diff --git a/_includes/_root/gas-station/Solution.java b/_includes/_root/gas-station/Solution.java deleted file mode 100644 index eebcb59..0000000 --- a/_includes/_root/gas-station/Solution.java +++ /dev/null @@ -1,27 +0,0 @@ -public class Solution { - public int canCompleteCircuit(int[] gas, int[] cost) { - - - int start = 0; - int from_start = 0; - - int total = 0; - - for(int i = 0; i < gas.length; i++){ - int left = gas[i] - cost[i]; - total += left; - from_start += left; - - if(from_start < 0){ - from_start = 0; - start = i + 1; // restart from next station - } - } - - if(total >= 0){ - return start; - } - - return -1; - } -} \ No newline at end of file diff --git a/_includes/_root/generate-parentheses/README.md b/_includes/_root/generate-parentheses/README.md deleted file mode 100644 index fdfe172..0000000 --- a/_includes/_root/generate-parentheses/README.md +++ /dev/null @@ -1,22 +0,0 @@ -## Recursion - -### `generateParenthesis(n - i)` and `generateParenthesis(i)` - -This problem is a bit like [Unique Binary Search Trees II](../unique-binary-search-trees-ii). - -Put left and right generateParenthesis together is OK. - - * `generateParenthesis(n - i)` + `generateParenthesis(i)` - * `generateParenthesis(i)` + `generateParenthesis(n - i)` - - -### Special `i = 1`: `generateParenthesis(n - 1)` and `generateParenthesis(1)` - -Another new way to generate parenthesis. - - * Surrounding :`(` + `generateParenthesis(n)` + `)` - -Same as `generateParenthesis(n - i)` and `generateParenthesis(i)` - - * `generateParenthesis(n - 1)` + `()` - * `()` + `generateParenthesis(n - 1)` diff --git a/_includes/_root/generate-parentheses/Solution.java b/_includes/_root/generate-parentheses/Solution.java deleted file mode 100644 index 26576e1..0000000 --- a/_includes/_root/generate-parentheses/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Solution { - public List generateParenthesis(int n) { - - if (n == 0) return new ArrayList(); - if (n == 1) return Arrays.asList(new String[]{"()"}); - - HashSet temp = new HashSet(); - - for(String s : generateParenthesis(n - 1)){ - temp.add("(" + s + ")"); - temp.add("()" + s); - temp.add(s + "()"); - } - - for(int i = 2; i < n - 1 ; i++){ - for(String s : generateParenthesis(n - i)){ - for(String ss : generateParenthesis(i)){ - - temp.add(ss + s); - temp.add(s + ss); - } - - } - } - - return new ArrayList(temp); - } -} diff --git a/_includes/_root/gray-code/README.md b/_includes/_root/gray-code/README.md deleted file mode 100644 index 0e6338a..0000000 --- a/_includes/_root/gray-code/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Formula - -Shamelessly, I copied it from [Gray Code on Wikipedia](http://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code). - -``` -G(N) = (B(n)/2) XOR B(n) -``` - diff --git a/_includes/_root/gray-code/Solution.java b/_includes/_root/gray-code/Solution.java deleted file mode 100644 index f8f383d..0000000 --- a/_includes/_root/gray-code/Solution.java +++ /dev/null @@ -1,15 +0,0 @@ -public class Solution { - public ArrayList grayCode(int n) { - - ArrayList rt = new ArrayList(); - - - for(int i = 0; i < Math.pow(2, n); i++){ - // G(N) = (B(n)/2) XOR B(n) - rt.add((i / 2) ^ i); - } - - return rt; - - } -} \ No newline at end of file diff --git a/_includes/_root/implement-strstr/README.md b/_includes/_root/implement-strstr/README.md deleted file mode 100644 index f407f61..0000000 --- a/_includes/_root/implement-strstr/README.md +++ /dev/null @@ -1,241 +0,0 @@ -## Brute force - -I'd not to be brainfucked and I write first brute force version. No surprisingly, Time Limit Exceeded. - -``` - -foreach i in haystack - foreach j in needle - if haystack[i + j] != needle[j] - i = i + 1 - retry - - found - -``` - -simple and easy but slow. - -## KMP Step by Step - -I only heard the KMP method, but I have no idea about how it goes. -now, I will show how do I understand KMP step by step. - - -### Needless Comparing - -lets say - -``` -0 1 2 3 4 5 6 -A B C D E F G -A B C E - -when - -i = 0 -j = 3 - - -if haystack[i + j] != needle[j] - i = i + 1 - retry - -``` - -`i` jump from `0` to `1`. but wait, why not jump to `3 (i + j) `? comparing `1` and `2` are obviously needless. - -### Where should `i` jump to on earth? - -e.g. - -``` -0 1 2 3 4 5 6 -A B A B A C G -A B A C - A B A C - A B A C - -i = 0 -j = 3 - -``` - -retry from `i = 3`? Wrong. it seems `i` should jump to `2` instead of `3` - -``` -0 1 2 3 -A B A C - A B A C - -i = 0 -j = 3 -``` - -mismatch at `3` indicates that `haystack[3 - 1] == needle[3 - 1]`. -In additional, `needle[3 - 1] == needle[0]`, so `i` jumps to `3` and then goes back `1` char to `2`, in the formula: `0 + 3 - 1 (i + j - 1)` - - -more complex example - -``` -0 1 2 3 4 5 -A B C A B C - A B C A B C - -i = 0 -j = 5 -``` - -mismatch at `5` indicates that `haystack[5 - 1] == needle[5 - 1]`. -In additional, `needle[5 - 2] == needle[0]` and `needle[5 - 1] == needle[1]`, so `i` jumps to `5 (i + j)` and then goes back `2` chars to `3`, in the formula: `0 + 5 - 2 (i + j - 2)` - - - -### How many chars does `needle[i]` go back? - -From above, `needle[i]` should go back `P` chars - -such that - -``` -needle[i - P] == needle[0] and needle[i - (P - 1)] == needle[1] and ... - -for n = 0 .. P - 1 - needle[i - P + n] == needle[0 + n] -``` - -the `P` here DO have name. In wikipedia or some other places, it was known as [needle's longest proper suffix which is a proper prefix](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#.22Partial_match.22_table_.28also_known_as_.22failure_function.22.29). I do not understand why they like brainfucking ppl :(. - - -now we can write some easy code to find all `P` of `needle[i]` to `P[i]`, `P[i]` here means how many chars should needle[i] go back. - - -The first brute force `P` finding version. Because I do not know how to calculate the `P`, I search from max possible value to zero. I hope codes below would help you understand what the `P` is - -``` - -here S.substring(i, j) == S[i] + S[i + 1] + ... S[j - 1] - - -for i in needle - Possible_P = i - 1 - - while Possible_P > 0 and needle.substring(0, Possible_P) != needle.substring(i - Possible_P, i) - Possible_P = Possible_P - 1 - - P[i] = Possible_P - - -``` - -as you can see - -`needle.substring(0, Possible_P)` is the prefix and `needle.substring(i - Possible_P, i)` is the suffix - - - -### Put them together (First working version KMP) - -``` - -for i in needle - Possible_P = i - 1 - - while Possible_P > 0 and needle.substring(0, Possible_P) != needle.substring(i - Possible_P, i) - Possible_P = Possible_P - 1 - - P[i] = Possible_P - - - -foreach i in haystack - foreach j in needle - if haystack[i + j] != needle[j] - i = i + j - P[i] - - i = MAX(i, 1) // at least jump 1 char, think j = 0, infinite looping - - retry - - found - -``` - -### Optimizing P finding - -Time limited again, last P finding method is silly and takes a long time to run. - -Each loop in needle only add `1` char, so the maximum value of `P[i]` is `P[i - 1] + 1` - -``` -for i in needle - Possible_P = P[i - 1] + 1 - - while Possible_P > 0 and needle.substring(0, Possible_P) != needle.substring(i - Possible_P, i) - Possible_P = Possible_P - 1 - - P[i] = Possible_P -``` - -and think can the case like `P[i - 1] = 10 and P[i] = 6` happens? - -No, becasue `P[i]` depends on `P[i - 1]`. - -`P[i - 1] = 10` means that in the string of `needle[0 .. i - 1 - 1]`, that the fist `10 chars(prefix) of needle[0 .. i - 1 - 1] = last 10 chars(suffix) of needle[0 .. i - 1 - 1]`. - -`P[i] = 6` means that in the string of `needle[0 .. i - 1]`, that the fist `6 chars(prefix) of needle[0 .. i - 1] = last 6 chars(suffix) of needle[0 .. i - 1]`. - - -So, `P[i]` should be `P[i - 1] + 1` or `0` - - -``` -for i in needle - Possible_P = P[i - 1] + 1 - - if needle.substring(0, Possible_P) != needle.substring(i - Possible_P, i) - Possible_P = 0 - - P[i] = Possible_P -``` - -Now, substring is also needless. `P[i - 1]` indicates that `needle.substring(0, P[i - 1 - 1]) == needle.substring(i - P[i - 1 - 1], i)`. -if any new char(`needle[i - 1]`) comes, checking `needle[0 + P[i - 1]] == needle[i - 1]` is enough. - - -e.g. - -``` -0 1 2 3 4 5 -A B C A B C - A B C A B C - ^ ^ - m n - -when i = 5 -P[5 - 1] = 1 (needle[0] == needle[3]) - -if needle[0 + 1] == needle[5 - 1] - P[5] = P[4] + 1 - -``` - -here we can see `m = 0 + P[i - 1]` and `n = i - 1` - - -### P finding Final version - - -``` -for i in needle - Possible_P = P[i - 1] + 1 - - if needle[0 + P[i - 1]] != needle[i - 1] - Possible_P = 0 - - P[i] = Possible_P -``` - - - diff --git a/_includes/_root/implement-strstr/Solution.java b/_includes/_root/implement-strstr/Solution.java deleted file mode 100644 index b606da4..0000000 --- a/_includes/_root/implement-strstr/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -public class Solution { - public String strStr(String haystack, String needle) { - - if(haystack == null) return null; - if(needle == null) return null; - - char[] _haystack = haystack.toCharArray(); - char[] _needle = needle.toCharArray(); - - if(_needle.length == 0) return haystack; - if(_haystack.length < _needle.length) return null; - - - int[] P = new int[_needle.length]; - - for(int j = 2; j < _needle.length; j++){ - - int k = 0; - - if(_needle[0 + P[j - 1]] == _needle[j - 1]){ - k = P[j - 1] + 1; - } - - P[j] = k; - } - - next: - for(int i = 0; i < _haystack.length; /*void*/){ - - for(int j = 0; j < _needle.length; j++){ - - if(i + j >= _haystack.length) return null; - - if(_haystack[i + j] != _needle[j]){ - i += Math.max(1, j - P[j]); - continue next; - } - } - - return new String(_haystack, i, _haystack.length - i); - } - - return null; - } -} \ No newline at end of file diff --git a/_includes/_root/insert-interval/README.md b/_includes/_root/insert-interval/README.md deleted file mode 100644 index c1944c5..0000000 --- a/_includes/_root/insert-interval/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Looks like [Merge Intervals](../merge-intervals) - -`Merge Intervals` does a sort inside the function, good news for us is that the input is already sorted. - -What we need to do is to [Search Insert Position](../search-insert-position), and insert the new interval there. (Insertion Sort) - - -Now call `Merge Intervals` without sort. diff --git a/_includes/_root/insert-interval/Solution.java b/_includes/_root/insert-interval/Solution.java deleted file mode 100644 index f63b911..0000000 --- a/_includes/_root/insert-interval/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List insert(List intervals, Interval newInterval) { - - int pos = intervals.size(); - - for(int i = 0; i < intervals.size(); i++){ - if(newInterval.start <= intervals.get(i).start){ - pos = i; - break; - } - } - - intervals.add(pos, newInterval); - - - ArrayList rt = new ArrayList(); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} diff --git a/_includes/_root/insertion-sort-list/README.md b/_includes/_root/insertion-sort-list/README.md deleted file mode 100644 index 2b10b0b..0000000 --- a/_includes/_root/insertion-sort-list/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Insertion Sort - - 1. Create a `dummy sorted linked list` - 1. take one node from the unsorted linked list and [Search Insert Position](../search-insert-position) in the `dummy sorted linked list` - 1. Insert the node to the `Insert Position` in the `dummy sorted linked list` - 1. repeat step 2 until there is no more nodes. - diff --git a/_includes/_root/insertion-sort-list/Solution.java b/_includes/_root/insertion-sort-list/Solution.java deleted file mode 100644 index f604a9b..0000000 --- a/_includes/_root/insertion-sort-list/Solution.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode insertionSortList(ListNode head) { - - if(head == null) return null; - if(head.next == null) return head; - - final ListNode _head = new ListNode(Integer.MIN_VALUE); - _head.next = head; - - head = head.next; - _head.next.next = null; - - next: - while(head != null){ - - ListNode taken = head; - head = head.next; - - - ListNode cur = _head.next; - ListNode last = _head; - - - while(cur != null){ - - if(cur.val > taken.val){ - // insert - last.next = taken; - taken.next = cur; - - continue next; - - } - - cur = cur.next; - last = last.next; - } - - last.next = taken; - taken.next = null; - - } - - - return _head.next; - - } -} \ No newline at end of file diff --git a/_includes/_root/integer-to-roman/README.md b/_includes/_root/integer-to-roman/README.md deleted file mode 100644 index 157850d..0000000 --- a/_includes/_root/integer-to-roman/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Opposite to [Roman to Integer](../roman-to-integer) - -This time, rollback the buffer instead of the number. - diff --git a/_includes/_root/integer-to-roman/Solution.java b/_includes/_root/integer-to-roman/Solution.java deleted file mode 100644 index 58dc6c6..0000000 --- a/_includes/_root/integer-to-roman/Solution.java +++ /dev/null @@ -1,61 +0,0 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - public String intToRoman(int num) { - - String buff = ""; - char last = 0; - int samecount = 0; - - while (num > 0){ - for(int i = N.length - 1; i >= 0; i--){ - if(num >= N[i]){ - num -= N[i]; - buff += C[i]; - - if(last == C[i]){ - samecount++; - }else{ - samecount = 0; - } - - - if(samecount == 3){ - int s = 5 * N[i]; - - buff = buff.substring(0, buff.length() - 4); - - if(!buff.isEmpty() && buff.charAt(buff.length() - 1) == C[i + 1]){ - s += N[i + 1]; - buff = buff.substring(0, buff.length() - 1); - } - - - return buff + C[i] + intToRoman(s) + intToRoman(num); - } - - last = C[i]; - break; - } - } - } - - return buff; - - } -} \ No newline at end of file diff --git a/_includes/_root/interleaving-string/README.md b/_includes/_root/interleaving-string/README.md deleted file mode 100644 index a3597b5..0000000 --- a/_includes/_root/interleaving-string/README.md +++ /dev/null @@ -1,89 +0,0 @@ -## Yet Another [Unique Paths](../unique-paths) - -put the strings onto the matrix - - - -``` -+---+---+---+---+---+---+---+ -| | * | a | a | b | c | c | -+---+---+---+---+---+---+---+ -| * | | | | | | | -+---+---+---+---+---+---+---+ -| d | | | | | | | -+---+---+---+---+---+---+---+ -| b | | | | | | | -+---+---+---+---+---+---+---+ -| b | | | | | | | -+---+---+---+---+---+---+---+ -| c | | | | | | | -+---+---+---+---+---+---+---+ -| a | | | | | | | -+---+---+---+---+---+---+---+ - -``` - -Paths for `aadbbcbcac`, from top-left ot bottom-right. each step can choose to go to the grid on the right or the grid on the bottom. - - * from `1,1` goto `1,2` use letter `a` in `aabcc` - * from `1,2` goto `1,3` use letter `a` in `aabcc` - * from `1,3` goto `2,3` use letter `d` in `dbbca` - * fork from `2,3`, the next step can be `2,4` or `3,3` - * ... - * until no next step or reach the bottom right grid. - - -``` -+---+---+---+---+---+---+---+ -| | * | a | a | b | c | c | 0 -+---+---+---+---+---+---+---+ -| * | 1 | 1 | 1 | | | | 1 -+---+---+---+---+---+---+---+ -| d | | | 1 | 1 | | | 2 -+---+---+---+---+---+---+---+ -| b | | | 2 | 1 | 1 | | 3 -+---+---+---+---+---+---+---+ -| b | | | 2 | | 1 | | 4 -+---+---+---+---+---+---+---+ -| c | | | 2 | 2 |1 2| | 5 -+---+---+---+---+---+---+---+ -| a | | | | |1 2|1 2| 6 -+---+---+---+---+---+---+---+ - 0 1 2 3 4 5 6 - -``` - -Paths for `aadbbbaccc` - - -``` -+---+---+---+---+---+---+---+ -| | * | a | a | b | c | c | -+---+---+---+---+---+---+---+ -| * | 1 | 1 | 1 | | | | -+---+---+---+---+---+---+---+ -| d | | | 1 | 1 | | | -+---+---+---+---+---+---+---+ -| b | | | 2 | 1 | | | -+---+---+---+---+---+---+---+ -| b | | | 2 | 1 | | | -+---+---+---+---+---+---+---+ -| c | | | | | | | -+---+---+---+---+---+---+---+ -| a | | | | | | | -+---+---+---+---+---+---+---+ - -``` - -No path can reach the bottom right grid. - -## [Dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) - -`P[i][j]` indicates that there is an `Interleaving String` formed by `S1[0..i - 1]` and `S2[0..j - 1]`. - - * `P[1][1]` = true - * `P[i][j] = (P[i - 1][j] || P[i][j - 1]) && (S3[i + j - 1] == S1[i - 1] || S3[i + j - 1] == S2[j - 1])` - - -I think Dynamic programming is brain fucking. Not as easy as the girds, but, essentially, they are the same. - diff --git a/_includes/_root/interleaving-string/Solution.java b/_includes/_root/interleaving-string/Solution.java deleted file mode 100644 index 1208d2e..0000000 --- a/_includes/_root/interleaving-string/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -public class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - - char[] S1 = s1.toCharArray(); - char[] S2 = s2.toCharArray(); - char[] S3 = s3.toCharArray(); - - if(S1.length + S2.length != S3.length) return false; - - int i; - int j; - - boolean[][] map = new boolean[S1.length + 1][S2.length + 1]; - // i -> s1, j -> s2 - - map[0][0] = true; - - for(i = 1; i <= S1.length; i++){ - map[i][0] = map[i - 1][0] && S1[i - 1] == S3[i - 1]; - } - - for(j = 1; j <= S2.length; j++){ - map[0][j] = map[0][j - 1] && S2[j - 1] == S3[j - 1]; - } - - for(i = 1; i <= S1.length; i++){ - for(j = 1; j <= S2.length; j++){ - - if(map[i - 1][j]){ - map[i][j] = S3[i + j - 1] == S1[i - 1]; - continue; - } - - if(map[i][j - 1]){ - map[i][j] = S3[i + j - 1] == S2[j - 1]; - continue; - } - - } - } - - return map[S1.length][S2.length]; - - } -} \ No newline at end of file diff --git a/_includes/_root/intersection-of-two-linked-lists/README.md b/_includes/_root/intersection-of-two-linked-lists/README.md deleted file mode 100644 index f5548cb..0000000 --- a/_includes/_root/intersection-of-two-linked-lists/README.md +++ /dev/null @@ -1,22 +0,0 @@ -## Two Lists with same length - - -``` - -A: a1 → a2 - ↘ - c1 → c2 → c3 - ↗ -B: b1 → b2 - - -``` - -Use two `iter`s go through the list, and compare each `val`. It is easy to find out the intersection point. - -## What if the length is not the same - -Make them the same. - - * find out two lists' length - * trim the longer one and remove the `overhead` diff --git a/_includes/_root/intersection-of-two-linked-lists/Solution.java b/_includes/_root/intersection-of-two-linked-lists/Solution.java deleted file mode 100644 index 5d78aa2..0000000 --- a/_includes/_root/intersection-of-two-linked-lists/Solution.java +++ /dev/null @@ -1,74 +0,0 @@ -/** -* Definition for singly-linked list. -* public class ListNode { -* int val; -* ListNode next; -* ListNode(int x) { -* val = x; -* next = null; -* } -* } -*/ -public class Solution { - - int len(ListNode head){ - - int len = 0; - ListNode iter = head; - - while(iter != null){ - - len++; - iter = iter.next; - } - - return len; - } - - ListNode trim(ListNode head, int count){ - - ListNode iter = head; - - while(iter != null && count > 0){ - - count--; - iter = iter.next; - } - - return iter; - } - - - public ListNode getIntersectionNode(ListNode headA, ListNode headB) { - - - int lenA = len(headA); - int lenB = len(headB); - int min = Math.min(lenA, lenB); - - ListNode iterA = trim(headA, lenA - min); - ListNode iterB = trim(headB, lenB - min); - - ListNode intersection = null; - - - while(iterA != null && iterB != null){ - - if(iterA.val != iterB.val){ - intersection = null; - } else if (intersection == null){ - intersection = iterA; - } - - iterA = iterA.next; - iterB = iterB.next; - } - - - if (iterA != null || iterB != null){ - return null; - } - - return intersection; - } -} diff --git a/_includes/_root/jump-game-ii/README.md b/_includes/_root/jump-game-ii/README.md deleted file mode 100644 index ce24ab0..0000000 --- a/_includes/_root/jump-game-ii/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## [Prim's algorithm](http://en.wikipedia.org/wiki/Prim's_algorithm) - -This solution looks like [Prim's algorithm](http://en.wikipedia.org/wiki/Prim's_algorithm). - - - * jump to the furthest reachable point - * update `maxjump` like [Jump Game](../jump-game) - * `count = count + 1` - * loop until reach the end - diff --git a/_includes/_root/jump-game-ii/Solution.java b/_includes/_root/jump-game-ii/Solution.java deleted file mode 100644 index 19b1101..0000000 --- a/_includes/_root/jump-game-ii/Solution.java +++ /dev/null @@ -1,21 +0,0 @@ -public class Solution { - public int jump(int[] A) { - int count = 0; - int laststep = 0; - - for(int i = 0; i < A.length - 1; /**/){ - - int maxstep = i + A[i]; - for(int j = laststep + 1; j <= i; j++){ - maxstep = Math.max(maxstep, j + A[j]); - } - - laststep = i; - i = maxstep; - - count++; - } - - return count; - } -} \ No newline at end of file diff --git a/_includes/_root/jump-game/README.md b/_includes/_root/jump-game/README.md deleted file mode 100644 index e6c80f6..0000000 --- a/_includes/_root/jump-game/README.md +++ /dev/null @@ -1,67 +0,0 @@ -## Simulating - -``` - 0 1 2 3 4 -A[2,3,1,1,4] -``` - -from A[0], can jump to every pos between `0` and `0 + A[0]` -from A[1], can jump to every pos between `1` and `1 + A[1]` - -so.. -from A[i], can jump to every pos between `i` and `i + A[i]` - -C[i] is a paper that help us to remember if we can jump to pos `i` - -``` - 0 1 2 3 4 -A[2,3,1,1,4] -C[0,0,0,0,0] -``` - -``` -for A[0] C[0 .. 0 + A[0]] = 1 -for A[1] C[1 .. 1 + A[1]] = 1 - -for A[i] C[i .. i + A[i]] = 1 -``` - -thus, code should be like below - -``` -C[0] = 1 -foreach i in A - if C[i] == 1 then - C[i .. i + A[i]] = 1 - -return C[last i of A] -``` - - -## Array C is not needed - -when we set -``` -C[i .. i + A[i]] = 1 -``` - -is equals - -``` -foreach i in A - C[0 .. max of i + A[i]] = 1 -``` - -is equals - -``` -maxjump = 0 -foreach i in A - maxjump = max(maxjump, i + A[i]) - -``` - -so `C[i]` can be replaced by `i < maxjump` - - -Removing C would save memory and the time used for setting them to 1 diff --git a/_includes/_root/jump-game/Solution.java b/_includes/_root/jump-game/Solution.java deleted file mode 100644 index 6ed7274..0000000 --- a/_includes/_root/jump-game/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -public class Solution { - - - - public boolean canJump(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(A.length == 0) return false; - - - int maxjump = 0; - - for(int i = 0; i < A.length; i++){ - if(i <= maxjump){ - if(i + A[i] < A.length - 1){ - maxjump = Math.max(maxjump, i + A[i]); - }else{ - return true; - } - } else { - return false; - } - } - - return false; - } -} \ No newline at end of file diff --git a/_includes/_root/largest-number/README.md b/_includes/_root/largest-number/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/largest-number/Solution.java b/_includes/_root/largest-number/Solution.java deleted file mode 100644 index c7f2116..0000000 --- a/_includes/_root/largest-number/Solution.java +++ /dev/null @@ -1,12 +0,0 @@ -public class Solution { - public String largestNumber(int[] num) { - - String[] ns = Arrays.stream(num).mapToObj(x -> "" + x).toArray(String[]::new); - - Arrays.sort(ns, (String x, String y) -> (y + x).compareTo(x + y)); - - if("0".equals(ns[0])) return "0"; - - return Arrays.stream(ns).collect(Collectors.joining()); - } -} diff --git a/_includes/_root/largest-rectangle-in-histogram/README.md b/_includes/_root/largest-rectangle-in-histogram/README.md deleted file mode 100644 index 5944c0b..0000000 --- a/_includes/_root/largest-rectangle-in-histogram/README.md +++ /dev/null @@ -1,248 +0,0 @@ -## Looks like [Trapping Rain Water](../trapping-rain-water) - -``` -[2, 1, 5, 6, 2, 3] - - +---+ - | | - +---+---+ - | | | - +---+---+ - | | | - +---+---+ +---+ - | | | | | -+---+ +---+---+---+---+ -| | | | | | | -+---+---+---+---+---+---+ -| | | | | | | -+---+---+---+---+---+---+ - - 2 1 5 6 2 3 [ Height ] - 0 1 2 3 4 5 [ Index ] - -``` - -[Loop invariant](http://en.wikipedia.org/wiki/Loop_invariant) with Stack/Queue - -In this case, we store the bars in non-descending order. -If any new bar breaks the order, we are sure that the heights of rectangles formed by the non-descending order bars have nothing to do with the new bar. - -In another words, we can now count the rectangles' area and update the max. - -Then, pack all saved bar into a dwarf but long one. -Imagine that there would be a dwarf but long one which could win the max rectangle prize. - -e.g. - -``` -[5, 6, 2, 3] - - - +---+ - | | -+---+---+ -| | | -+---+---+ -| | | -+---+---+ +---+ -| | | | | -+---+---+---+---+ -| | | | | -+---+---+---+---+ -| | | | | -+---+---+---+---+ - - 0 1 2 3 [ Index ] - - -``` - -No matter what the height the bar `3` is, rectangles formed by bar `0..3` can not benefit form the height of bar `3`. - -Meanwhile, It is time to calculate the rectangles' area formed bar `0..2`. - - -## Animation - -a `bar` is like - - -``` -Bar { height, width } -``` - -new bar's height is `2` put it into storage - -``` -Storage: - -[{height=2, width=1}] - - - - - - - - - -+---+ -| | -+---+ -| | -+---+ -``` - -new bar's height is `1`, less than `2`, so count rectangles now. - -``` - - - - - - - - - -+---+ -| | -+---+---+ -| | | -+---+---+ - 0 1 [Index] -``` - -2 rectangles formed by bar `0..1`, the max area is `2` - -Then, pack those bars into one. - -``` -Storage: -[{height=1, width=2}] - - - - - - - - - - -+-------+ -| | -+-------+ - - 0 [ Index ] - -``` - -new bars with height `5` and `6` - -``` -Storage: -[{height=1, width=2}, {height=5, width=1}, {height=5, width=1}] - - +---+ - | | - +---+---+ - | | | - +---+---+ - | | | - +---+---+ - | | | - +---+---+ - | | | -+-------+---+---+ -| | | | -+-------+---+---+ - - 0 1 2 [ Index ] - -``` - -new bar with height `2`, it is time to update max. - -``` -Storage: -[{height=1, width=2}, {height=5, width=1}, {height=5, width=1}] - - +---+ - | | - +---+---+ - | | | - +---+---+ - | | | - +---+---+ - | | | - +---+---+---+ - | | | | -+-------+---+---+---+ -| | | | | -+-------+---+---+---+ - - 0 1 2 3 [ Index ] -``` - -rectangles are `6 * 1`, `5 * 2` , `1 * 4`. - -Pack them again. - -``` -Storage: -[{height=1, width=2}, {height=2, width=3}] - - - - - - - - - - +-----------+ - | | -+-------+-----------+ -| | | -+-------+-----------+ - - 0 1 [ Index ] -``` - -new bar with height `3` - - -``` -Storage: -[{height=1, width=2}, {height=2, width=3}, {height=3, width=1}] - - - - - - - - +---+ - | | - +-----------+---+ - | | | -+-------+-----------+---+ -| | | | -+-------+-----------+---+ - - 0 1 2 [ Index ] -``` - -### Deal with left-overs - -Fire another area calculating is ok. -But, a more elegant method is that you can add a fake bar with height `0`. - - -`Simple is better than complex. -- Zen of Python` - - - - - diff --git a/_includes/_root/largest-rectangle-in-histogram/Solution.java b/_includes/_root/largest-rectangle-in-histogram/Solution.java deleted file mode 100644 index 4228568..0000000 --- a/_includes/_root/largest-rectangle-in-histogram/Solution.java +++ /dev/null @@ -1,52 +0,0 @@ -public class Solution { - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } -} \ No newline at end of file diff --git a/_includes/_root/length-of-last-word/README.md b/_includes/_root/length-of-last-word/README.md deleted file mode 100644 index 25c3c81..0000000 --- a/_includes/_root/length-of-last-word/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Split and count - - * split by `' '` - * count the length of the last one diff --git a/_includes/_root/length-of-last-word/Solution.java b/_includes/_root/length-of-last-word/Solution.java deleted file mode 100644 index af1a9b9..0000000 --- a/_includes/_root/length-of-last-word/Solution.java +++ /dev/null @@ -1,21 +0,0 @@ -public class Solution { - public int lengthOfLastWord(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s == null) return 0; - - char[] chars = s.toCharArray(); - - int upper = chars.length - 1; - while(upper >=0 && chars[upper] == ' ') upper--; - - int len = 0; - for(int i = 0; i<= upper; i++){ - if(chars[i] == ' ')len = 0; - else len++; - } - - return len; - - } -} \ No newline at end of file diff --git a/_includes/_root/letter-combinations-of-a-phone-number/README.md b/_includes/_root/letter-combinations-of-a-phone-number/README.md deleted file mode 100644 index 695e6d0..0000000 --- a/_includes/_root/letter-combinations-of-a-phone-number/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## DFS - -An easy problem - - - * build a map contains the number to all possible char - * search throught each possible char diff --git a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java b/_includes/_root/letter-combinations-of-a-phone-number/Solution.java deleted file mode 100644 index 85e7a81..0000000 --- a/_includes/_root/letter-combinations-of-a-phone-number/Solution.java +++ /dev/null @@ -1,42 +0,0 @@ -public class Solution { - - static final char[][] CHAR_MAP = { - {}, // 0 - {}, // 1 - { 'a', 'b', 'c'}, //2 - { 'd', 'e', 'f'}, //3 - { 'g', 'h', 'i'}, //4 - { 'j', 'k', 'l'}, //5 - { 'm', 'n', 'o'}, //6 - { 'p', 'q', 'r', 's'}, //7 - { 't', 'u', 'v'}, //8 - { 'w', 'x', 'y', 'z'}, //9 - }; - - ArrayList rt; - char[] stack; - - void find(char[] digits, int p){ - - if(p == digits.length){ - rt.add(new String(stack)); - }else{ - - int num = (int) (digits[p] - '0'); - - for(char pc : CHAR_MAP[num]){ - stack[p] = pc; - find(digits, p + 1); - } - } - } - - public List letterCombinations(String digits) { - - rt = new ArrayList<>(); - stack = new char[digits.length()]; - - find(digits.toCharArray(), 0); - return rt; - } -} diff --git a/_includes/_root/linked-list-cycle-ii/README.md b/_includes/_root/linked-list-cycle-ii/README.md deleted file mode 100644 index 20727d4..0000000 --- a/_includes/_root/linked-list-cycle-ii/README.md +++ /dev/null @@ -1,25 +0,0 @@ -## More work after [Linked List Cycle I](../linked-list-cycle) - -To find where the cycle begins, we can use a fast-slow pointer. - -The faster one walks `length of the cycle` steps before the slower one, and then, the slower one start to walk. -Where the faster one and slower one meet is the point that the cycle begins. - -## Measure the length of the cycle - -After the fast-slow runners encounter, let them go on running until they will meet at some point. - -If slow-runner walks `1` step each loop, when they meet again, the slow-runner will walk `length of the cycle` steps. - - -So, code might be like - -``` - -loop until fast meets slow - - if not meet first time - length = length + 1 - - -``` diff --git a/_includes/_root/linked-list-cycle-ii/Solution.java b/_includes/_root/linked-list-cycle-ii/Solution.java deleted file mode 100644 index bc2e4fd..0000000 --- a/_includes/_root/linked-list-cycle-ii/Solution.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode detectCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - ListNode fast = head; - ListNode slow = head; - - boolean meet = false; - - int lenc = 0; - - while ( slow.next != null){ - - slow = slow.next; - - if(slow == null) return null; - - if(fast.next == null) return null; - - fast = fast.next.next; - - if(fast == null) return null; - - if(slow == fast) { - - if(meet) break; - - meet = true; - } - - if(meet){ - lenc++; - } - } - - if(meet){ - - slow = head; - fast = head; - for(int i = 0; i< lenc; i++){ - fast = fast.next; - } - - while(slow != fast){ - slow = slow.next; - fast = fast.next; - } - - - return slow; - - } - - return null; - } -} \ No newline at end of file diff --git a/_includes/_root/linked-list-cycle/README.md b/_includes/_root/linked-list-cycle/README.md deleted file mode 100644 index 90ab4ec..0000000 --- a/_includes/_root/linked-list-cycle/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## Fast slow pointer - -A linked list with cycle. - - -``` -1----->-----2----->-------3 - | | - | | - ^ V - | | - | | - 5------<------4 - -``` - -let two people run in it, one take 1 step each time, the other take 2 steps each time. -They will meet at a point after some time running. - -imagine month and week, the first day of month and the first day of week will meet sometimes. - - -So, let a fast runner and a slow runner run in the linked list - - * they will collide if the linked list has a cycle. - * the faster one will find the exit if there is no cycle. diff --git a/_includes/_root/linked-list-cycle/Solution.java b/_includes/_root/linked-list-cycle/Solution.java deleted file mode 100644 index c40f172..0000000 --- a/_includes/_root/linked-list-cycle/Solution.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public boolean hasCycle(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return false; - - ListNode fast = head; - ListNode slow = head; - - - while(slow.next != null){ - - if(fast.next == null) return false; - - fast = fast.next.next; - - if(fast == null) return false; - - slow = slow.next; - - if(fast == slow) return true; - } - - return false; - } -} \ No newline at end of file diff --git a/_includes/_root/longest-common-prefix/README.md b/_includes/_root/longest-common-prefix/README.md deleted file mode 100644 index edb528d..0000000 --- a/_includes/_root/longest-common-prefix/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Brute force - - * Use an `offset` starting from `0`. - * set `offset = offset + 1` if all strings have same char at `offset`. - * loop until `offset` exceed any string's length or chars at `offset` are not the same. diff --git a/_includes/_root/longest-common-prefix/Solution.java b/_includes/_root/longest-common-prefix/Solution.java deleted file mode 100644 index e4af631..0000000 --- a/_includes/_root/longest-common-prefix/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -public class Solution { - public String longestCommonPrefix(String[] strs) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int p = 0; - - if(strs.length == 0) return ""; - if(strs.length == 1) return strs[0]; - - - here: - - while(true){ - - if( p >= strs[0].length() ) break; - - char c = strs[0].charAt(p); - - for(String str : strs){ - if(str.length() <= p || str.charAt(p) != c) break here; - } - - p++; - - } - - return strs[0].substring(0, p); - - - - } -} \ No newline at end of file diff --git a/_includes/_root/longest-consecutive-sequence/README.md b/_includes/_root/longest-consecutive-sequence/README.md deleted file mode 100644 index 599a702..0000000 --- a/_includes/_root/longest-consecutive-sequence/README.md +++ /dev/null @@ -1,117 +0,0 @@ -## Aggregating consecutive numbers - -Before - -``` -[100, 4, 200, 1, 3, 2] -``` - -After - -``` -[(100), (4, 1, 3, 2), (200)] -``` - -### One way to achieve - -Two collections one is for input, the other is for aggregated nums - - * take a number away from input - * create a tuple to contain the aggregated nums - * search all possiable nums and take them away from input - * loop until the input array is empty - - - -``` -nums : [100, 4, 200, 1, 3, 2] - -aggr : [] -``` - -move `100` into `aggr` - - -``` -nums : [4, 200, 1, 3, 2] - -aggr : [(100)] -``` - -`99` and `101` is not in the `nums`, so go to next - - -move `4` into `aggr` - - -``` -nums : [200, 1, 3, 2] - -aggr : [(100), (4)] -``` - -`5` is not in the `nums` - -`3` is in the `nums`, so move `3` into `aggr` - - -``` -nums : [200, 1, 2] - -aggr : [(100), (4, 3)] -``` - -`2` is in the `nums`, so move `2` into `aggr` - -``` -nums : [200, 1] - -aggr : [(100), (4, 3, 2)] -``` - -`1` is in the `nums`, so move `1` into `aggr` - -``` -nums : [200] - -aggr : [(100), (4, 3, 2, 1)] -``` - -`0` is not in the `nums`, so go to next - -move `200` into `aggr` - -``` -nums : [] - -aggr : [(100), (4, 3, 2, 1), (200)] -``` - -In this problem, the sequence is no need to be stored, update the longest length is enough. - -so, code may be like - -``` - -while nums is not emtpy - - len = 1 - - n = nums.poll() - - // search forward - for i in n .. INFINITE - - if i in nums - remove i from nums - len = len + 1 - - // search backward - for i in n .. -INFINITE - - if i in nums - remove i from nums - len = len + 1 - - longest = MAX(longest, len) -``` diff --git a/_includes/_root/longest-consecutive-sequence/Solution.java b/_includes/_root/longest-consecutive-sequence/Solution.java deleted file mode 100644 index 98fc2d9..0000000 --- a/_includes/_root/longest-consecutive-sequence/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -public class Solution { - public int longestConsecutive(int[] num) { - - HashSet nums = new HashSet(); - - for(int n : num){ - nums.add(n); - } - - int longest = 0; - - for(final int n : num){ - - int l = 1; - - int nn = n; - - nums.remove(n); - - while(nums.contains(++nn)){ - l++; - nums.remove(nn); - } - - nn = n; - - while(nums.contains(--nn)){ - l++; - nums.remove(nn); - } - - longest = Math.max(longest, l); - } - - return longest; - - } -} \ No newline at end of file diff --git a/_includes/_root/longest-palindromic-substring/README.md b/_includes/_root/longest-palindromic-substring/README.md deleted file mode 100644 index bbc0966..0000000 --- a/_includes/_root/longest-palindromic-substring/README.md +++ /dev/null @@ -1,67 +0,0 @@ -## Leetcode Blog Version - -Here is the [Leetcode Blog Version](http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html). -This is a classic problem. I write my first leetcode accepted version based on that. - - -## My own words version - -Brute force + isPalindromic will run out of time. - -### Recursive - - * `length 1 substring`: all are palindromic - * `length 2 substring`: only if two char are same - -What if `length 3` - -``` - -length 3 = length 1 + two char - -0 1 2 3 4 -a b c b a -+ ^ -| | -+---+ - - -0 1 2 4 4 -a b c b a - + ^ - | | - +---+ - -``` - - * `length n` = inner `length n - 2` is palindromic AND (first char == last char) - - -### Store `length n` into `P[lenght n][start index]` - - * `P[1][3] = true` means that the substring starts from index 3 and 1 char long is palindromic. - * `P[5][2] = true` means that the substring starts from index 2 and 5 char long is NOT palindromic. - - -a matrix for `abcba` - -``` - - 0 1 2 3 4 - a b c b a -1 1 1 1 1 1 -2 0 0 0 0 - -3 0 1 0 - - -4 0 0 - - - -5 1 - - - - -^ -l -e -n - -``` - -With the matrix, we can fill up the martix by `P[len][i] = P[len -2][i + 1] && S[i] == S[i + len -1]`. - - -Note: the `length 0` is useless, so just using `P[len - 1]` for `len`. diff --git a/_includes/_root/longest-palindromic-substring/Solution.java b/_includes/_root/longest-palindromic-substring/Solution.java deleted file mode 100644 index 6184350..0000000 --- a/_includes/_root/longest-palindromic-substring/Solution.java +++ /dev/null @@ -1,40 +0,0 @@ -public class Solution { - public String longestPalindrome(String s) { - - char[] S = s.toCharArray(); - - if(S.length == 0) return ""; - - boolean[][] P = new boolean[S.length][S.length]; - - int maxi = 0; - int maxlen = 1; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - if(S[i] == S[i + 2 - 1]){ - P[2 - 1][i] = true; - maxi = i; - maxlen = 2; - } - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - - if(P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]){ - P[len - 1][i] = true; - maxi = i; - maxlen = len; - } - } - } - - return s.substring(maxi, maxi + maxlen); - } -} diff --git a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md deleted file mode 100644 index 0c5f96c..0000000 --- a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/README.md +++ /dev/null @@ -1,36 +0,0 @@ -## Relative of [Minimum Window Substring](../minimum-window-substring) - -This problem is a litte easier than [Minimum Window Substring](../minimum-window-substring). - -## Loop invariant - -Assume that `S` is a `string with at most two distinct char` - -when a new char `c` comes: - * append it to `S`'s right - * trim from `S`'s left, remove one char until `S` is a `string with at most two distinct char` - -``` -S = 'aabb' - -new char c = 'c' - -S = 'aabbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'abbc' - -S is not `string with at most two distinct char` -so remove a from S - -S = 'bbc' - -``` - - -## Finding max - -after each loop, `S` is a `string with at most two distinct char`. but, its length changes. -what we need is to find the max length. diff --git a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/Solution.java b/_includes/_root/longest-substring-with-at-most-two-distinct-characters/Solution.java deleted file mode 100644 index 6f239ec..0000000 --- a/_includes/_root/longest-substring-with-at-most-two-distinct-characters/Solution.java +++ /dev/null @@ -1,68 +0,0 @@ -public class Solution { - - static class Context { - int start = 0; - int end = 0; - - Map counts = new HashMap(); - - int len(){ - return end - start + 1; - } - - void add(Character c) { - Integer i = counts.get(c); - if(i == null){ - i = 0; - } - - i++; - - counts.put(c, i); - } - - void remove(Character c){ - Integer i = counts.remove(c); - if(i == null){ - return; - } - - i--; - - if(i > 0){ - counts.put(c, i); - } - } - } - - public int lengthOfLongestSubstringTwoDistinct(String s) { - - char[] S = s.toCharArray(); - - if(S.length == 0) return 0; - - int max = 1; - - Context context = new Context(); - - for(int i = 0; i < S.length; i++){ - Character c = S[i]; - - context.add(c); - context.end = i; - - // need trim to 2 - - for(int j = context.start; context.counts.size() > 2 ;j++) { - Character _c = S[j]; - context.remove(_c); - context.start = j + 1; - } - - max = Math.max(context.len(), max); - } - - - return max; - } -} diff --git a/_includes/_root/longest-substring-without-repeating-characters/README.md b/_includes/_root/longest-substring-without-repeating-characters/README.md deleted file mode 100644 index e4d3237..0000000 --- a/_includes/_root/longest-substring-without-repeating-characters/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Loop invariant - -Set a `barrier`, such that, `s[barrier..current]` contains no repeating characters. -when a new char comes, update the `barrier` if needed. - -the `current - barrier + 1` is the length of the substring. - - -``` - -barrier = 0 -foreach i in s - - while s[barrier .. i] contains characters - - barrier = barrier + 1 - - max = MAX(max, current - barrier + 1) - -``` - diff --git a/_includes/_root/longest-substring-without-repeating-characters/Solution.java b/_includes/_root/longest-substring-without-repeating-characters/Solution.java deleted file mode 100644 index 10a18fd..0000000 --- a/_includes/_root/longest-substring-without-repeating-characters/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Solution { - public int lengthOfLongestSubstring(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(s == null) return 0; - char[] str = s.toCharArray(); - if(str.length == 0) return 0; - - - int max = 1; - - int barrier = 0; - - for(int i = 1; i < str.length; i++){ - for(int j = i - 1; j >= barrier;j--){ - if(str[i] == str[j]){ - barrier = j + 1; - break; - } - } - - max = Math.max(max, i - barrier + 1); - } - - - return max; - - } -} \ No newline at end of file diff --git a/_includes/_root/longest-valid-parentheses/README.md b/_includes/_root/longest-valid-parentheses/README.md deleted file mode 100644 index 9a4cce0..0000000 --- a/_includes/_root/longest-valid-parentheses/README.md +++ /dev/null @@ -1,74 +0,0 @@ -## Counting while [Valid Parentheses](../valid-parentheses) - -When a pair of valid parentheses is found, just add `2` to count. - -However, the counting method is a bit tricky. Show you using animation - -### Animation - -This method adds a counting stack. - -``` -input [ ( ( ) ( ) ) ] - -count [] -stack [] - - i - -``` - -No match put `)` and `(` into stack - -``` -input [ ) ( ) ) ] - -count [ 0 0 ] -stack [ ( ( ] - - i - -``` - - - -found matches pop stack and `count[1] = count[1] + 2` - -``` -input [ ( ) ) ] - -count [ 0 2 ] -stack [ ( ] - - i - -``` - -just two steps. - -found another matches `(` and `)` pop stack and `count[1] = count[1] + 2` - -``` -input [ ] - -count [ 0 4 ] -stack [ ] - - i - -``` - - -found matches, but, this time, `count[0] = count[0] + 2` is not enough. - -It should be `count[0] = count[0] + 2 + count[1]`, because that here `0` matches parentheses indicates that the current parentheses is enclosing the `1..current`. - - -Generally, when meets a match, - -``` -count[stack.size()] = count[stack.size()] + 2 + count[stack.size() + 1] -``` - -then reset the `count[stack.size() + 1]` to `0`. - diff --git a/_includes/_root/longest-valid-parentheses/Solution.java b/_includes/_root/longest-valid-parentheses/Solution.java deleted file mode 100644 index 744f00d..0000000 --- a/_includes/_root/longest-valid-parentheses/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -public class Solution { - public int longestValidParentheses(String s) { - if(s == null) return 0; - - char[] chars = s.toCharArray(); - if(chars.length <= 1) return 0; - - LinkedList stack = new LinkedList(); - - int[] count = new int[chars.length]; - int max = 0; - - for(int i = 0 ; iLinkedHashMap instance with the - * specified initial capacity, load factor and ordering mode. - * - * @param initialCapacity the initial capacity - * @param loadFactor the load factor - * @param accessOrder the ordering mode - true for - * access-order, false for insertion-order - * @throws IllegalArgumentException if the initial capacity is negative - * or the load factor is nonpositive - */ - public LinkedHashMap(int initialCapacity, - float loadFactor, - boolean accessOrder) { - super(initialCapacity, loadFactor); - this.accessOrder = accessOrder; - } -``` - -here the parameter `accessOrder` can be used to refresh newly accessed value - -and - -override - -``` - protected boolean removeEldestEntry(Map.Entry eldest) { - return false; - } -``` -to remove old entry - - -## DIY - -I'd not do this at work. but it is a good chance to learn and practice writing a `HashMap` - -### HashMap - - * Storing data - - 1. use an array Entry[] to store the data - 1. `put` Entry[hash(key)] = value - 1. `get` return Entry[hash(key)] - - - * Dealing with hash conflict - - 1. add next pointer to Entry in order to store key with same hash - 1. `put` add to Entry.next - 1. `get` search through the linked list and if equals then retun Entry.value - - * Good news: no need to expand space if no enough space - -### Remember the order - - * Move any element to the top (`get`, `put`) - * Remove the element on the tail (`put`) - -To achieve above, just threading each Entry to a doubly linked list. - - -## Put them together - -``` -Entry { key, value, hashnext, linknext, linkprev } -``` - -### GET(k) - -``` - -foreach E linked list Entry[hash(k)] - if E.key == k - moveToLinkTop(E) - return E.value - -not found - -``` - -### PUT(k, v) - -``` - -if over capacity - E = tail of doubly linked list - remove E from linked list Entry[hash(E.key)] - -E = E(k,v) - -add E to linked list Entry[hash(E.key)] -moveToLinkTop(E) - -``` - - diff --git a/_includes/_root/lru-cache/Solution.java b/_includes/_root/lru-cache/Solution.java deleted file mode 100644 index 907851d..0000000 --- a/_includes/_root/lru-cache/Solution.java +++ /dev/null @@ -1,150 +0,0 @@ -public class LRUCache { - - static class Entry { - int key; - int value; - - Entry hashnext; - - Entry linknext; - Entry linkprev; - } - - Entry[] data; - - int capacity; - int size; - - Entry head; - Entry tail; - - public LRUCache(int capacity) { - this.capacity = capacity; - data = new Entry[capacity + capacity/2 + 3]; - size = 0; - - head = new Entry(); - tail = new Entry(); - - head.linknext = tail; - tail.linkprev = head; - } - - int hash(int key){ - return key % capacity; - } - - void moveToHead(Entry e){ - - Entry before = e.linkprev; - Entry after = e.linknext; - - before.linknext = after; - after.linkprev = before; - - addBeforeHead(e); - } - - void addBeforeHead(Entry e){ - Entry chead = head.linknext; - chead.linkprev = e; - head.linknext = e; - - e.linkprev = head; - e.linknext = chead; - } - - Entry _get(int key){ - int h = hash(key); - Entry e = data[h]; - - while(e != null){ - if(e.key == key){ - moveToHead(e); - return e; - } - - e = e.hashnext; - } - - return null; - } - - public int get(int key) { - Entry e = _get(key); - - if(e == null){ - return -1; - } - - return e.value; - } - - void removeOneFromTail(){ - Entry e = tail.linkprev; - - tail.linkprev = e.linkprev; - tail.linkprev.linknext = tail; - - int h = hash(e.key); - - Entry d = data[h]; - - if(d == e || d.key == e.key){ - data[h] = e.hashnext; - return; - } - - Entry p = d; - d = d.hashnext; - - while(d != null){ - - if(d == e){ - p.hashnext = e.hashnext; - return; - } - p = d; - d = d.hashnext; - } - - } - - public void set(int key, int value) { - if(capacity == 0) return; - - Entry e = _get(key); - if(e != null){ - e.value = value; - return; - } - - if(size >= capacity){ - removeOneFromTail(); - size--; - } - - e = new Entry(); - - e.key = key; - e.value = value; - - addBeforeHead(e); - - int h = hash(e.key); - Entry d = data[h]; - - if(d == null){ - data[h] = e; - } else { - while(d.hashnext != null){ - d = d.hashnext; - } - - d.hashnext = e; - } - - size++; - - } -} \ No newline at end of file diff --git a/_includes/_root/majority-element/README.md b/_includes/_root/majority-element/README.md deleted file mode 100644 index 69b0d60..0000000 --- a/_includes/_root/majority-element/README.md +++ /dev/null @@ -1,18 +0,0 @@ -## [A Linear Time Majority Vote Algorithm](http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html) - -## Game: How to find 10 IPs which are flooding your server - -Imagine that there is an arena which can on only contains 10 people. -Every people is holding an IP. - -Now, throw the accessing IPs into the arena to hit the people with rule below: - - * a people is holding the same IP will get health `+1` - * if no people is holding the IP, the IP will hit a people randomly, that people's health `-1` - * people with health 0 will be kicked out of the arena and replace by new people hold current IP. - -at the end, people left in the arena with high health value are obviously the attackers. - - - - diff --git a/_includes/_root/majority-element/Solution.java b/_includes/_root/majority-element/Solution.java deleted file mode 100644 index ea635a7..0000000 --- a/_includes/_root/majority-element/Solution.java +++ /dev/null @@ -1,18 +0,0 @@ -public class Solution { - public int majorityElement(int[] num) { - int m = num[0]; - int c = 1; - - for(int i = 1; i < num.length; i++){ - if(num[i] == m){ - c++; - }else if (c > 1){ - c--; - }else{ // c == 1 && num[i] != m - m = num[i]; - } - } - - return m; - } -} diff --git a/_includes/_root/max-points-on-a-line/README.md b/_includes/_root/max-points-on-a-line/README.md deleted file mode 100644 index 0c854af..0000000 --- a/_includes/_root/max-points-on-a-line/README.md +++ /dev/null @@ -1,74 +0,0 @@ -## Something about line - - * Two Distinct Point - * [Two-point form](http://en.wikipedia.org/wiki/Linear_equation#Two-point_form) - - -so a line should be like - - -``` -Line { Point1, Point2 } - -function check_on_line(l, p) - #check p on l using Two-point form - p1, p2 <- l - return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x) - -``` - - -## Loop invariant to find all `Line` and their `point_count`s - -Init: Build a collection(`C`) for `Line`s and put first `Line` with first two `Point` into it. - - - 1. take a new `Point` p - 1. `point_count++` to any `Line` in `C` with `p` on it - 1. if p is not on any `Line` in `C`, create `Line`s with `p` and all former `Point`s - 1. put new `Line`s into `C` - - -``` -foreach p in input - - on_some_line = False - - foreach l in C - if check_on_line(l, c) - l.point_count = l.point_count + 1 - on_some_line = True - - if not on_some_line - foreach _p in input before p - l = build new Line with _p and p - add l to C - -``` - -### Newly Built Line's point_count - -It is wrong that newly built `Line.point_count = 0`. Because the new `Line l` may cross some `Line` in `C`, -and the cross point may be the in the input points. - -In that case, the new `Line` should have its `point_count = count of former p on it` . - -Patched `not on_some_line` block - - -``` - if not on_some_line - foreach _p in input before p - l = build new Line with _p and p - - l.point_count = count of point input before p on l - - add l to C -``` - -## Finding max - -Search `C` to find the max count. - - - diff --git a/_includes/_root/max-points-on-a-line/Solution.java b/_includes/_root/max-points-on-a-line/Solution.java deleted file mode 100644 index 9a990e2..0000000 --- a/_includes/_root/max-points-on-a-line/Solution.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Definition for a point. - * class Point { - * int x; - * int y; - * Point() { x = 0; y = 0; } - * Point(int a, int b) { x = a; y = b; } - * } - */ -public class Solution { - - static class Line{ - - Point p1; - Point p2; - - int pointCount; - - Line(Point p1, Point p2){ - this.p1 = p1; - this.p2 = p2; - - this.pointCount = 2; - } - - boolean on(int x, int y){ - return (x - p1.x) * (p2.y - p1.y) == (y - p1.y) * (p2.x - p1.x); - } - - boolean on(Point p){ - return on(p.x, p.y); - } - } - - public int maxPoints(Point[] points) { - - if(points.length < 2) return points.length; - - ArrayList lines = new ArrayList(); - - lines.add(new Line(points[0], points[1])); - - for(int i = 2; i < points.length; i++){ - boolean on = false; - for(Line line : lines){ - if(line.on(points[i])){ - line.pointCount++; - on = true; - } - } - - if(!on){ - for(int j = 0; j < i; j++){ - Line l = new Line(points[j], points[i]); - lines.add(l); - - for(int k = 0; k < i; k++){ - if(j != k && l.on(points[k])){ - l.pointCount++; - break; - } - - } - } - } - } - - - int max = Integer.MIN_VALUE; - - for(Line line : lines){ - if(line.pointCount > max) max = line.pointCount; - } - - return max; - - } -} \ No newline at end of file diff --git a/_includes/_root/maximal-rectangle/README.md b/_includes/_root/maximal-rectangle/README.md deleted file mode 100644 index 2aa9e70..0000000 --- a/_includes/_root/maximal-rectangle/README.md +++ /dev/null @@ -1,70 +0,0 @@ -## Guessing - -``` -1 1 1 1 1 1 1 -0 0 0 0 1 0 0 -1 1 0 1 0 1 0 -1 1 0 1 1 1 0 -1 1 1 1 0 1 0 -1 0 0 1 0 1 0 - -``` - -I do not where to start and I can not even count how many rectangles are there. - -The title reminds me that there is a problem called [Largest Rectangle in Histogram](../largest-rectangle-in-histogram). - - -## Histogram in the matrix - -from the top to bottom, we can build histograms like below - -``` -1 1 1 1 1 1 1 a -0 0 0 0 2 0 0 b -1 1 0 1 0 1 0 c -2 2 0 2 1 2 0 d -3 3 1 3 0 3 0 e -4 0 0 4 0 4 0 f - -``` - -here means - - * `line a` has a set histograms with heights `1 1 1 1 1 1 1` - * `line b` has a set histograms with heights `0 0 0 0 2 0 0` - * `line c` has a set histograms with heights `1 1 0 1 0 1 0` - * ... - * `line f` has a set histograms with heights `4 0 0 4 0 4 0` - -so we can call [Largest Rectangle in Histogram](../largest-rectangle-in-histogram) and update the max. - - -Similarly, from the left to right, we can also build histograms like below - - -``` -1 2 3 4 5 6 7 -0 0 0 0 1 0 0 -1 2 0 1 0 1 0 -1 2 0 1 2 3 0 -1 2 3 4 0 1 0 -1 0 0 1 0 1 0 - -a b c d e f g -``` - - -code may be like - - -``` - -convert martix into histograms - -foreach h in histograms - - max = MAX(largestRectangleArea(h), max) - - -``` diff --git a/_includes/_root/maximal-rectangle/Solution.java b/_includes/_root/maximal-rectangle/Solution.java deleted file mode 100644 index 68873f4..0000000 --- a/_includes/_root/maximal-rectangle/Solution.java +++ /dev/null @@ -1,116 +0,0 @@ -public class Solution { - public int maximalRectangle(char[][] matrix) { - int x; - int y; - - int mx = matrix.length; - if(mx == 0) return 0; - int my = matrix[0].length; - if(my == 0) return 0; - - - int[][] _matrix = new int[mx][my]; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - - int max = 0; - - for (x = 0; x < mx; x++){ - for(y = my - 1; y > 0; y--){ - if(matrix[x][y - 1] != '0' && matrix[x][y] != '0'){ - _matrix[x][y - 1] += _matrix[x][y]; - } - } - } - - for(y = 0; y < my; y++){ - - int h[] = new int[mx]; - - for(x = 0; x < mx; x++) - h[x] = _matrix[x][y]; - - max = Math.max(max, largestRectangleArea(h)); - } - - _matrix = new int[mx][my]; - - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++) { - _matrix[x][y] = matrix[x][y] == '1' ? 1 : 0; - } - } - - for (y = 0; y < my; y++){ - for(x = mx - 1; x > 0; x--){ - if(matrix[x - 1][y] != '0' && matrix[x][y] != '0'){ - _matrix[x - 1][y] += _matrix[x][y]; - } - } - } - - for(x = 0; x < mx; x++){ - max = Math.max(max, largestRectangleArea(_matrix[x])); - } - - - return max; - } - - - static class Rect { - int width = 1; - int height; - - Rect(int height){ - this.height = height; - } - } - - public int largestRectangleArea(int[] height) { - - if(height.length == 0) return 0; - - height = Arrays.copyOf(height, height.length + 1); - height[height.length - 1] = 0; - - Deque stack = new LinkedList(); - - stack.push(new Rect(height[0])); - - int max = 0; - - next: - for(int i = 1; i < height.length; i++){ - int h = height[i]; - - Rect r = new Rect(h); - - int sl = 0; - while(true){ - - if(stack.isEmpty() || h > stack.peek().height){ - stack.push(r); - continue next; - } - - - Rect left = stack.pop(); - - sl += left.width; - max = Math.max(max, left.height * sl); - - r.width = 1 + sl ; // merge left into new - } - - } - - return max; - } -} \ No newline at end of file diff --git a/_includes/_root/maximum-depth-of-binary-tree/README.md b/_includes/_root/maximum-depth-of-binary-tree/README.md deleted file mode 100644 index ed7de83..0000000 --- a/_includes/_root/maximum-depth-of-binary-tree/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Definition - -``` -maxDepth = 0 [if root is null] - MAX(maxDepth(root.left), maxDepth(root.right)) + 1 [otherwise ] -``` diff --git a/_includes/_root/maximum-depth-of-binary-tree/Solution.java b/_includes/_root/maximum-depth-of-binary-tree/Solution.java deleted file mode 100644 index df368fd..0000000 --- a/_includes/_root/maximum-depth-of-binary-tree/Solution.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int maxDepth(TreeNode root) { - - if(root == null) return 0; - - return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; - } -} diff --git a/_includes/_root/maximum-gap/README.md b/_includes/_root/maximum-gap/README.md deleted file mode 100644 index 3365673..0000000 --- a/_includes/_root/maximum-gap/README.md +++ /dev/null @@ -1,32 +0,0 @@ -## `O(n)` Sort - -The problem requires `O(n)` time complexity, and it looks something like sort. -[Bucket Sort](http://en.wikipedia.org/wiki/Bucket_sort) and [Radix sort](http://en.wikipedia.org/wiki/Radix_sort) -are the two well known `O(n)` sort. - -Maybe an `O(32n)` radix sort will work well. - -## Bucket sort version - -> First, I choose N buckets and divide nums into [0, avg) [avg, 2avg) .... [navg, inf) and do a regular bucket sort. -Through, this solution got accepted by leetcode, I found there is a better solution. - -the most ideal gap is `max - min`. so if there is `N` elements, there will be `N - 1` gaps, -the `maximum gap` must be greater than `(max - min) / (N - 1)`. - -Like bucket sort, we put nums into `(max - min) / (max_gap) + 1` buckets, -but, this time a good news is that we do not need to sort the numbers in the buckets, -what we need is only to remember the max and min of the bucket. -The reason is easy to understand: the number between the max and min of the bucket will not yield a bigger gap. - -after bucketing, numbers are like - -``` -[MIN] [MIN] [MIN] -[ ] [ ] ... [ ] -[MAX] [MAX] [MAX] -``` - -The work left is to measure the gap between `bucket[i - 1].max` and `bucket[i].min`. - -Note: the will be some emtpy buckets, skip them. diff --git a/_includes/_root/maximum-gap/Solution.java b/_includes/_root/maximum-gap/Solution.java deleted file mode 100644 index 4f0498d..0000000 --- a/_includes/_root/maximum-gap/Solution.java +++ /dev/null @@ -1,52 +0,0 @@ -public class Solution { - - static class Bucket { - int min = Integer.MAX_VALUE; - int max = Integer.MIN_VALUE; - - void add(int n){ - min = Math.min(n, min); - max = Math.max(n, max); - } - } - - public int maximumGap(int[] num) { - if (num.length < 2) return 0; - - int max = Integer.MIN_VALUE; - int min = Integer.MAX_VALUE; - - for(int i = 0; i < num.length; i++){ - max = Math.max(max, num[i]); - min = Math.min(min, num[i]); - } - - - int gap = (int) Math.ceil((double)(max - min) / (num.length - 1)); - int n = (max - min) / gap + 1; - - Bucket[] buckets = new Bucket[n]; - - for(int i = 0; i < num.length; i++){ - int index = (num[i] - min) / gap; - - if(buckets[index] == null) buckets[index] = new Bucket(); - - buckets[index].add(num[i]); - } - - int maxGap = Integer.MIN_VALUE; - - int prev = min; - - for(int i = 0; i < buckets.length; i++){ - if(buckets[i] == null) continue; - - maxGap = Math.max(maxGap, buckets[i].min - prev); - - prev = buckets[i].max; - } - - return maxGap; - } -} diff --git a/_includes/_root/maximum-product-subarray/README.md b/_includes/_root/maximum-product-subarray/README.md deleted file mode 100644 index 462aaf3..0000000 --- a/_includes/_root/maximum-product-subarray/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Yet another [Maximum Subarray](../maximum-subarray) - -We cannot just drop negative histories this time, instead, -They may grow into bigger positive numbers in the future. - -To make [Maximum Subarray](../maximum-subarray) works on this problem, -just add a variable to remember the negative histories. - - -When a negative number comes, -the negative history may trun into a number greater than positive history. -Swap the positive and negative histories. diff --git a/_includes/_root/maximum-product-subarray/Solution.java b/_includes/_root/maximum-product-subarray/Solution.java deleted file mode 100644 index efd7e72..0000000 --- a/_includes/_root/maximum-product-subarray/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Solution { - public int maxProduct(int[] A) { - - int max = A[0]; - int positive_history = A[0]; - int negative_history = A[0]; - - for(int i = 1; i < A.length; i++){ - - positive_history *= A[i]; - negative_history *= A[i]; - - if(negative_history > positive_history){ - int t = negative_history; - negative_history = positive_history; - positive_history = t; - } - - positive_history = Math.max(A[i], positive_history); - negative_history = Math.min(A[i], negative_history); - - - max = Math.max(max, positive_history); - } - - return max; - } -} diff --git a/_includes/_root/maximum-subarray/README.md b/_includes/_root/maximum-subarray/README.md deleted file mode 100644 index b297640..0000000 --- a/_includes/_root/maximum-subarray/README.md +++ /dev/null @@ -1,24 +0,0 @@ -## History: Remember? Forget? - -If there is some bad things yesterday, we gotta forget it. - -This is the same in finding maximum subarray. ^_^ - - * drop pre-subarray if the sum is negative - * merge current and pre-subarray if the sum of pre-subarray is positive - - -``` -foreach number in A - - if history < 0 - history = number - else - history = history + number - - - max = MAX(history, max) // remember the beautiful day - - -``` - diff --git a/_includes/_root/maximum-subarray/Solution.java b/_includes/_root/maximum-subarray/Solution.java deleted file mode 100644 index ede5dd2..0000000 --- a/_includes/_root/maximum-subarray/Solution.java +++ /dev/null @@ -1,20 +0,0 @@ -public class Solution { - public int maxSubArray(int[] A) { - - int max = A[0]; - int history = A[0]; - - for(int i = 1; i < A.length; i++){ - if(history < 0){ - history = A[i]; - }else{ - history += A[i]; - } - - max = Math.max(max, history); - - } - - return max; - } -} diff --git a/_includes/_root/median-of-two-sorted-arrays/README.md b/_includes/_root/median-of-two-sorted-arrays/README.md deleted file mode 100644 index e4f9527..0000000 --- a/_includes/_root/median-of-two-sorted-arrays/README.md +++ /dev/null @@ -1,159 +0,0 @@ -## Something must know about [Median](http://en.wikipedia.org/wiki/Median) - - * odd: median of {3, 3, 5, 9, 11} is 5 - * even: the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 - - -## Kth of two sorted array in `O(log(m + n))` - -### `O(m + n)` - -Acting like [Merge Sorted Array](../merge-sorted-array), just take first `k` elements. - - -But, I will show you a brute force version, because it can be optimized to `O(log(m + n))` easily. - - -### `O(m + n)` Brute Force - -search through kth of `Array M` and `Array N` - -Code is like - - -``` -foreach n in array m and array n - - if isKth(n) - found - -``` - -Core tech is how to determine if `n` is the kth. - -#### isKth - -Imagine that take `k` elements from `Array M` and `Array N`, `m` elements from `Array M` and `n` from `Array N`. - -such that, the `Kth` element must be `MAX(mth of Array M, nth of Array N)` - -e.g. - -``` -Array M [1, 3, 5, 7, 9] -Array N [0, 2, 4, 6, 8] - - -Array M [1, 3, 5, 7, 9] - ^ - | - +-+ - | -Array N [0, 2, 4, 6, 8] - - -try to put the nth element after the mth element - -``` - - * take 3 elements from M: `[1, 3, 5]` - * take 4(7-3) elements from N: `[0, 2, 4, 6]` - * the 7th element is: `MAX(5,6)` - * 8th..10th `[7, 8, 9]` are greater than or equals to the 7th - -that is - - * k = m + n - * kth = MAX(ArrayM[m], ArrayN[n]) - * elements in `ArrayM[m + 1..end]` and `ArrayN[n + 1..end]` must be greater than or equals to the kth - - -So checking kth code is like - -``` -function isKth(m, ArrayM, ArrayN) - n = k - m - - return ArrayN[n] <= ArrayM[m] <= ArrayN[n + 1] - -``` - -### `O(log(m + n))` Binary Search - -with `isKth`, we can write a binary search version using binary search template. - - -``` - -search arrayM - -while s < e - - m = (s + e) / 2 - - if iskth(m, arrayM, arrayN) - return ArrayM[mid] - - - // solve this later - s = m + 1 or e = m - -``` - -this will take `O(log(m))` time, if kth is not found, do the same to `ArrayN`. - -#### `s = m + 1 or e = m` - -when mid is not kth, we are going to remove half of the elements that must not contain the kth. - - -``` -searching Array M - -Array M [0, 2, 4, 6, 8] - s m e - -Array N [1, 3, 5, 7, 9] - n -k = 7 -n = k - m -``` - - * ArrayM[m] = 4 - * ArrayN[n] = 7 - -If `ArrayM[m]` is not the kth, that is, `ArrayM[m]` is less than `ArrayN[n]` or `ArrayN[n + 1]`. - -When `ArrayM[m] < ArrayM[n]`, we must enlarge the `ArrayM[m]`, so `s = m + 1` if we want `ArrayM[m]` to be the kth. - -Similarly, we must diminish ArrayM[m] if `ArrayM[m] > ArrayM[n]` - -In code: - -``` -if ArrayM[m] < ArrayM[n] - // enlarge ArrayM[m] - s = m + 1 -else - // diminish ArrayM[m] - e = m -``` - -## Put them together - -``` - -len = len(A) + len(B) - -if len is odd - kth(A,B, len/2) -else - (kth(A,B, len/2) + kth(A,B, len/2 + 1)) / 2 - - -``` - -## Note - - * Array in my code start from `0` - * Sometimes, no element on any index, just treat it as -INFINITE diff --git a/_includes/_root/median-of-two-sorted-arrays/Solution.java b/_includes/_root/median-of-two-sorted-arrays/Solution.java deleted file mode 100644 index 4d7a58c..0000000 --- a/_includes/_root/median-of-two-sorted-arrays/Solution.java +++ /dev/null @@ -1,80 +0,0 @@ -public class Solution { - - int safe(int[] X, int i){ - - if ( i < 0) return Integer.MIN_VALUE; - - if ( i >= X.length) return Integer.MAX_VALUE; - - return X[i]; - } - - int kth(int[] A, int[] B, int k){ - - if (A.length == 0) - return B[k]; - - if (B.length == 0) - return A[k]; - - if (k == 0) - return Math.min(A[0], B[0]); - - if (A.length == 1 && B.length == 1){ - // k must be 1 - return Math.max(A[0], B[0]); - } - - int s = 0; - int e = A.length; - - while ( s < e ){ - - int m = (s + e) / 2; - - int n = k - m; - - if ( A[m] <= safe(B, n) ) { - if (n == 0 || A[m] >= safe(B, n - 1)) { - return A[m]; - } - } - - if ( safe(B, n) <= A[m] ){ - if (m == 0 || safe(B, n) >= A[m - 1]) { - return B[n]; - } - } - - if ( A[m] < safe(B, n) ) { - s = m + 1; - } else { - e = m; - } - - } - - if (A[A.length - 1] < B[0]){ - return B[k - A.length]; - } else { - return kth(B, A, k); - } - - } - - - public double findMedianSortedArrays(int A[], int B[]) { - // median of {3, 3, 5, 9, 11} is 5 - // the median of {3, 5, 7, 9} is (5 + 7) / 2 = 6 wikipedia - - int s = A.length + B.length; - final int k = s / 2; - - if(s % 2 == 1){ - return kth(A, B, k); - }else{ - return (kth(A, B, k - 1) + kth(A, B, k)) / 2.0; - } - - } -} \ No newline at end of file diff --git a/_includes/_root/merge-intervals/README.md b/_includes/_root/merge-intervals/README.md deleted file mode 100644 index aca4814..0000000 --- a/_includes/_root/merge-intervals/README.md +++ /dev/null @@ -1,64 +0,0 @@ -## Merging - -``` - +------+ +----------------+ - | | | | -+---------------+ +-------------+ | -| | | | | | | | -+---+------+----+ +---+---------+------+ - - figure. 1 figure. 2 - -``` - - * figure. 1 - - An interval contains another interval, the merged one is the bigger one. - - * figure. 2 - - An interval overlaps another interval, the merged one is smaller start and bigger end - - -``` -function merge(i1. i2) - - return { start = MIN(i1.start, i2.start), end = MAX(i1.end, i2.end) } - -``` - -## Merge using a stack [Loop invariant] - -Assume that all intervals into a stack and all intervals are sorted by `start`. -The top two intervals in the stack are the smallest in `start`. - -If the top two cant be merged into one, the smaller one must cant be merged with any other intervals. -in another word, the smaller one can be put into final result set. - - -``` - -stack with sorted intervals - -while stack is not empty - - smallest = stack.pop() - secondary smallest = stack.pop() - - if can merge (overlap or contain) - merged = merge(smallest, secondary smallest) - stack.push(merged) - - else - - put smallest into results - - stack.push(secondary smallest) - - - -``` - - - - diff --git a/_includes/_root/merge-intervals/Solution.java b/_includes/_root/merge-intervals/Solution.java deleted file mode 100644 index efab953..0000000 --- a/_includes/_root/merge-intervals/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for an interval. - * public class Interval { - * int start; - * int end; - * Interval() { start = 0; end = 0; } - * Interval(int s, int e) { start = s; end = e; } - * } - */ -public class Solution { - public List merge(List intervals) { - - ArrayList rt = new ArrayList(); - - Collections.sort(intervals, new Comparator() { - public int compare(Interval o1, Interval o2) { - return o1.start - o2.start; - } - }); - - LinkedList s = new LinkedList(intervals); - - while (s.size() > 1) { - Interval i1 = s.pop(); - Interval i2 = s.pop(); - - if (i1.end >= i2.start) { - s.push(new Interval(i1.start, Math.max(i1.end, i2.end))); - } else { - s.push(i2); - rt.add(i1); - } - } - - rt.addAll(s); - - return rt; - } -} diff --git a/_includes/_root/merge-k-sorted-lists/README.md b/_includes/_root/merge-k-sorted-lists/README.md deleted file mode 100644 index 584f9d7..0000000 --- a/_includes/_root/merge-k-sorted-lists/README.md +++ /dev/null @@ -1,34 +0,0 @@ -## Merge each two - -If you can [Merge Two Sorted Lists](../merge-two-sorted-lists), then you can merge k by merging each two using a stack. - -code - -``` -put lists into a stack - -while stack has more than 2 lists - - merged = mergeTwoLists(stack.pop(), stack.pop()) - - stack.push(merged) - -``` - -Leetcode accpected the code above at Oct 2013. -But, the code got a `Time Limit Exceeded` when I change `ArrayList` to `List`. (`ArrayList` is used on old version leetcode) - - -## Reduce the time complexity to O(nlgn) - -`O(nlgn)` reminds me that something is call `MergeSort`. So just write code like a `MergeSort`. - - -``` -functino mergeKLists(lists) - left = mergeKLists(k / 2 lists) - right = mergeKLists(k / 2 lists) - - return merge(left, right) - -``` diff --git a/_includes/_root/merge-k-sorted-lists/Solution.java b/_includes/_root/merge-k-sorted-lists/Solution.java deleted file mode 100644 index 3760de2..0000000 --- a/_includes/_root/merge-k-sorted-lists/Solution.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode mergeTwoLists(ListNode l1, ListNode l2) { - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - } - - public ListNode mergeKLists(List lists) { - - final int size = lists.size(); - - if(size == 0) return null; - if(size == 1) return lists.get(0); - if(size == 2) return mergeTwoLists(lists.get(0), lists.get(1)); - - return mergeTwoLists(mergeKLists(lists.subList(0, size / 2)), mergeKLists(lists.subList(size / 2, size))); - } -} diff --git a/_includes/_root/merge-sorted-array/README.md b/_includes/_root/merge-sorted-array/README.md deleted file mode 100644 index f626951..0000000 --- a/_includes/_root/merge-sorted-array/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Core tech of MergeSort - -Merge is the core technology of MergeSort, that is why it was named MergeSort. - -``` - -convert input array -> left_part and right_part - -left_sorted_part = MergeSort(left_part) -right_sorted_part = MergeSort(right_part) - -Merge(left_sorted_part, right_sorted_part) - -``` - -## Merging - - 1. taking one (`l`) from `left_sorted_part` - 1. taking one (`r`) from `right_sorted_part` - 1. find the smaller(`s`) one in `l` and `r` - 1. put `s` into `result array` - 1. put bigger one back to `left_sorted_part` or `right_sorted_part` - 1. loop to step 1 until one is empty diff --git a/_includes/_root/merge-sorted-array/Solution.java b/_includes/_root/merge-sorted-array/Solution.java deleted file mode 100644 index c937f40..0000000 --- a/_includes/_root/merge-sorted-array/Solution.java +++ /dev/null @@ -1,33 +0,0 @@ -public class Solution { - public void merge(int A[], int m, int B[], int n) { - - int pa = 0; - int pb = 0; - int up = 0; - - while(pa < m + pb && pb < n){ - - int a = A[pa]; - int b = B[pb]; - - if (a < b){ - pa++; - }else{ - // shift up - for(int i = pb + m; i > pa ; i--){ - A[i] = A[i - 1]; - } - - A[pa] = b; - pa++; - pb++; - } - - } - - for( ; pb < n; pb++){ - A[pb + m] = B[pb]; - } - - } -} \ No newline at end of file diff --git a/_includes/_root/merge-two-sorted-lists/README.md b/_includes/_root/merge-two-sorted-lists/README.md deleted file mode 100644 index 58a6a8a..0000000 --- a/_includes/_root/merge-two-sorted-lists/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Same as [Merge Sorted Array](../merge-sorted-array) - -Linked list version is better, because `ListNode` is pointer already. diff --git a/_includes/_root/merge-two-sorted-lists/Solution.java b/_includes/_root/merge-two-sorted-lists/Solution.java deleted file mode 100644 index 514d87b..0000000 --- a/_includes/_root/merge-two-sorted-lists/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } -} \ No newline at end of file diff --git a/_includes/_root/min-stack/README.md b/_includes/_root/min-stack/README.md deleted file mode 100644 index 08dfc28..0000000 --- a/_includes/_root/min-stack/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Constant time means to remember the min value - -Update the min value when `push` and `pop`. - - * push: easy! just update the min value if the new number is less than the current `min value` - * pop : bad ! need to rollback to a former min value if the current `min value` is poped - -what we need is a non-ascending container for backing up the numbers. - -``` -MinStack = { - non_ascending_stack_for_rollback - stack_for_all -} -``` - -### The stack - -[LinkedList](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html) is a good one. -And it is easy to build your own stack. - -Note: at first, I use array to build my stack, but `Arrays.copyOf` caused time limited. - diff --git a/_includes/_root/min-stack/Solution.java b/_includes/_root/min-stack/Solution.java deleted file mode 100644 index 56459e1..0000000 --- a/_includes/_root/min-stack/Solution.java +++ /dev/null @@ -1,66 +0,0 @@ -class MinStack { - - static class Stack { - - static class Node { - int val; - Node next; - Node prev; - } - - Node head = new Node(); - int size = 0; - - public void push(int x) { - Node n = new Node(); - n.val = x; - n.prev = head; - - head.next = n; - head = n; - - size++; - } - - public void pop() { - head = head.prev; - size--; - } - - public int top() { - return head.val; - } - } - - Stack data = new Stack(); - Stack mins = new Stack(); - - public void push(int x) { - data.push(x); - - if(mins.size == 0 || getMin() >= x){ - mins.push(x); - } - } - - public void pop() { - int last = data.top(); - data.pop(); - - if(last <= getMin()){ - mins.pop(); - } - } - - public int top() { - return data.top(); - } - - public int getMin() { - if(mins.size > 0){ - return mins.top(); - } - - throw new IllegalStateException(); - } -} diff --git a/_includes/_root/minimum-depth-of-binary-tree/README.md b/_includes/_root/minimum-depth-of-binary-tree/README.md deleted file mode 100644 index 1725bf2..0000000 --- a/_includes/_root/minimum-depth-of-binary-tree/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Oppsite to [Maximum Depth of Binary Tree](../maximum-depth-of-binary-tree) - -Definition is a litte more complex than `maxDepth` - -``` -minDepth = 0 [empty tree ] - 1 [root is leaf ] - minDepth(root.left) + 1 [root has only left child ] - minDepth(root.right) + 1 [root has only right child] - MIN(minDepth(root.left), minDepth(root.right)) + 1 [otherwise ] -``` - diff --git a/_includes/_root/minimum-depth-of-binary-tree/Solution.java b/_includes/_root/minimum-depth-of-binary-tree/Solution.java deleted file mode 100644 index e1e9fde..0000000 --- a/_includes/_root/minimum-depth-of-binary-tree/Solution.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public int minDepth(TreeNode root) { - - if(root == null) return 0; - if(root.left == null && root.right == null) return 1; - - if(root.left != null && root.right == null) return minDepth(root.left) + 1; - if(root.left == null && root.right != null) return minDepth(root.right) + 1; - - return Math.min(minDepth(root.left), minDepth(root.right)) + 1; - - } -} diff --git a/_includes/_root/minimum-path-sum/README.md b/_includes/_root/minimum-path-sum/README.md deleted file mode 100644 index a1c91dc..0000000 --- a/_includes/_root/minimum-path-sum/README.md +++ /dev/null @@ -1,65 +0,0 @@ -## Picking up numbers on [Unique Paths](../unique-paths) - -From top left to the right bottom there is `n` [Unique Paths](../unique-paths). - -Picking up the numbers alone each path and sum them, we can collect all `Path Sum`. - - -e.g. a matrix with numbers - - -``` -+---+---+ -| 1 | 3 | -+---+---+ -| 2 | x | -+---+---+ -``` - - -`grid x` has `2` unique paths and `2` `path sum`s - - * 1 + 3 + x - * 1 + 2 + x (minimum) - -There are `2` viable paths to `grid x`, the grid on the left side of `grid x` and the grid on top of `grid x`. -We can choose the smaller path sum viable one, that will minimize path sum to `grid x`. - - -## Grid x - -``` -+---+---+---+---+---+---+---+ -| | | | | | | | -+---+---+---+---+---+---+---+ -| | | | | | | | -+---+---+---+---+---+---+---+ -| | | | m | | | | -+---+---+---+---+---+---+---+ -| | | n | x | | | | -+---+---+---+---+---+---+---+ -| | | | | | | | -+---+---+---+---+---+---+---+ -| | | | | | | | -+---+---+---+---+---+---+---+ -``` - -Assume that - - * `grid m` has a minimum path sum `m` - * `grid n` has a minimum path sum `n` - -So - -the minimum path sum `grid x` is MIN(m, n) + x - -## Fill up the matrix - - -Generally, `P[x][y]` is minimum path sum from top left. - - * `P[x][y] = MIN(P[x - 1][y], P[x][y - 1]) + grid[x][y]` - -the overall answer is in the right bottom grid. - -such filling up process is well know as [Dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) diff --git a/_includes/_root/minimum-path-sum/Solution.java b/_includes/_root/minimum-path-sum/Solution.java deleted file mode 100644 index 129901d..0000000 --- a/_includes/_root/minimum-path-sum/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Solution { - public int minPathSum(int[][] grid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - - int mx = grid.length; - if(mx == 0) return 0; - - int my = grid[0].length; - - for(int x = 1; x < mx ; x++){ - grid[x][0] += grid[x - 1][0]; - } - - for(int y = 1; y < my ; y++){ - grid[0][y] += grid[0][y - 1]; - } - - for(int x = 1; x < mx; x++){ - for(int y = 1; y < my; y++){ - grid[x][y] += Math.min(grid[x - 1][y], grid[x][y - 1]); - } - } - - return grid[mx - 1][my - 1]; - } -} \ No newline at end of file diff --git a/_includes/_root/minimum-window-substring/README.md b/_includes/_root/minimum-window-substring/README.md deleted file mode 100644 index f0b4d1f..0000000 --- a/_includes/_root/minimum-window-substring/README.md +++ /dev/null @@ -1,79 +0,0 @@ -## What is window substring like - -``` -S = "ADOBECODEBANC" -T = "ABC" -``` - -Minimum window is "BANC". A string with 1 `A`, 1 `B` and 1 `C`. - -Something you shuold notice: - - * if a substring is a window string, it plus any string is also a window string. - - `ADOBEC` is a window string, so `ADOBECODE` is a window string too. - - * if a window string's left most or right most character, lets say `c`, is in `T` and the window string has more character `c` than `T` has, removing the `c` from the window string will not break that the remaining string is a window string. - - `ADOBECODEBA` has 2 `A`, and more than `T` has (1 `A`). so, after remove `A` from left or right, the string remains a window string (`ADOBECODEB` is a window string). - - -## Loop invariant to find all possiable window string - -Assume that we had found a window string, `W`. - -Then - - 1. When a new char comes, `W` + new char = `WN` is also a window. (Rule 1) - 1. Trim the new window string, `WN`, from the left part, remove any char that is redundant to have a window string. (Rule 2) - -Code looks like - -``` - -W = a window string in S - -foreach c after W in S - - WN = W + c - - // Trim left - - foreach _c in WN - - if _c can be remove from WN - remove _c from the left part of WN - else - break - - W = WN - -``` - -### Finding the first `W` - -the `W` should have any char in `T`, this problem is like the `Check concatenation using count sum` in [Substring with Concatenation of All Words](../substring-with-concatenation-of-all-words). - -Use a map `need`, stores how many chars are needed. - -Use a map `seen`, stores how many chars are seen. - -Those maps are not only used in finding `W`, but also in triming redundant from `WN`. - - -This last problem is when the `W` is found. -Like [Substring with Concatenation of All Words](../substring-with-concatenation-of-all-words), just use a `counter`, -When `seen` is added, just add 1 to the counter. - -The time `counter == T.length` is the time we first found `W`. - - - -_Note_: -a char in `seen[c]` can contribute at most `need[c]` count to the `counter`. - - - - - - diff --git a/_includes/_root/minimum-window-substring/Solution.java b/_includes/_root/minimum-window-substring/Solution.java deleted file mode 100644 index bf5ad7b..0000000 --- a/_includes/_root/minimum-window-substring/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -public class Solution { - public String minWindow(String S, String T) { - char[] s = S.toCharArray(); - char[] t = T.toCharArray(); - - if ( t.length == 0) return ""; - if ( t.length > s.length ) return ""; - - - int mstart = 0; - int mend = -1; - - int gstart = 0; - int gend = 0; - - int[] need = new int[256]; - int[] seen = new int[256]; - - int checksum = 0; - - for(char c : t){ - need[(int)c]++; - } - - for(/*void*/; gend < s.length; gend++ ){ - - int i = (int)s[gend]; - if(need[i] > 0){ - seen[i]++; - - if(seen[i] <= need[i]) - checksum++; - } - - - if(checksum == t.length){ - - if(mend < 0) mend = s.length - 1; - - for(/*void*/; gstart <= gend; gstart++){ - - i = (int)s[gstart]; - if(need[i] > 0){ - if( seen[i] > need[i] ){ - seen[i]--; - } else { - break; - } - } - } - - if(gend - gstart < mend - mstart ){ - mstart = gstart; - mend = gend; - } - - } - - } - - - return S.substring(mstart, mend + 1); - } -} \ No newline at end of file diff --git a/_includes/_root/missing-ranges/README.md b/_includes/_root/missing-ranges/README.md deleted file mode 100644 index 1c0fb88..0000000 --- a/_includes/_root/missing-ranges/README.md +++ /dev/null @@ -1,63 +0,0 @@ -## Loop invariant - -init range is lower -> upper - -when a new number comes, the number divide the range into two ranges. -the left range must be a missing range. just output it. - - -``` -R = [0 -> 99] -S = [0, 1, 3, 50, 75] - ^ - | -``` - -`0` divide `[0 -> 99]` into `empty range` and `[1 -> 99]` - -``` -R = [1 -> 99] -S = [1, 3, 50, 75] - ^ - | -``` - -`1` divide `[1 -> 99]` into `empty range` and `[2 -> 99]` - -``` -R = [2 -> 99] -S = [3, 50, 75] - ^ - | -``` - -`3` divide `[2 -> 99]` into `[2]` and `[4 -> 99]` - -`[2]` is a missing, output. - - -``` -R = [4 -> 99] -S = [50, 75] - ^ - | -``` - -`50` divide `[4 -> 99]` into `[4 -> 49]` and `[51 -> 99]` - -`[4 -> 49]` is a missing, output. - - -``` -R = [51 -> 99] -S = [75] - ^ - | -``` - -`75` divide `[51 -> 99]` into `[51 -> 74]` and `[76 -> 99]` - -`[51 -> 74]` is a missing, output. - - -the last one `[76 -> 99]` is a missing range too. diff --git a/_includes/_root/missing-ranges/Solution.java b/_includes/_root/missing-ranges/Solution.java deleted file mode 100644 index 32511ad..0000000 --- a/_includes/_root/missing-ranges/Solution.java +++ /dev/null @@ -1,52 +0,0 @@ -public class Solution { - - static class Range { - int start; - int end; - - Range(int start, int end){ - this.start = start; - this.end = end; - } - - public String toString(){ - if(start == end) return "" + start; - - return start + "->" + end; - } - - boolean valid(){ - return end >= start; - } - - void addMeIfValid(List l){ - if(valid()){ - l.add(toString()); - } - } - } - - public List findMissingRanges(int[] A, int lower, int upper) { - - List rt = new ArrayList(); - - Range current = new Range(lower, upper); - - for(int i = 0; i < A.length; i++){ - if(A[i] > current.end) break; - - if(A[i] >= current.start){ - Range r = new Range(current.start, A[i] - 1); - - r.addMeIfValid(rt); - - current.start = A[i] + 1; - } - - } - - current.addMeIfValid(rt); - - return rt; - } -} diff --git a/_includes/_root/multiply-strings/README.md b/_includes/_root/multiply-strings/README.md deleted file mode 100644 index a880356..0000000 --- a/_includes/_root/multiply-strings/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## Final Boss - -After [Add Two Numbers](../add-two-numbers), [Add Binary](../add-binary) and [Plus One](../plus-one), here comes the final Boss. :-0 - - -### Multiply and Transfer Carry - - * create a `(m + n) array` as a paper: `m` digits * `n` digits resluts at most a `m + n` digits number. Think 99 * 99. - * each two digit multiply and save the onto the paper - * transfer the carry like [Add Two Numbers](../add-two-numbers) diff --git a/_includes/_root/multiply-strings/Solution.java b/_includes/_root/multiply-strings/Solution.java deleted file mode 100644 index b77b33e..0000000 --- a/_includes/_root/multiply-strings/Solution.java +++ /dev/null @@ -1,41 +0,0 @@ -public class Solution { - public String multiply(String num1, String num2) { - - int[] paper = new int[num1.length() + num2.length()]; - - Arrays.fill(paper, 0); - - char[] _num1 = num1.toCharArray(); - char[] _num2 = num2.toCharArray(); - - for (int i = 0; i < _num2.length; i++) { - for (int j = 0; j < _num1.length; j++) { - paper[paper.length - (i + j + 2)] += (_num1[j] - '0') * (_num2[i] - '0'); - } - } - - - // add - - for (int i = 0; i < paper.length - 1; i++) { - paper[i + 1] += paper[i] / 10; - paper[i] %= 10; - - } - - String s = ""; - for(int i = paper.length - 1; i > 0 ; i--){ - - if(paper[i] == 0 && "".equals(s)) - continue; - - s += paper[i]; - } - - s += paper[0]; - - - return s; - - } -} \ No newline at end of file diff --git a/_includes/_root/n-queens-ii/README.md b/_includes/_root/n-queens-ii/README.md deleted file mode 100644 index 21a340b..0000000 --- a/_includes/_root/n-queens-ii/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Same as [N-Queens I](../n-queens) - -`count = count + 1` when a solution is found. diff --git a/_includes/_root/n-queens-ii/Solution.java b/_includes/_root/n-queens-ii/Solution.java deleted file mode 100644 index ff737b8..0000000 --- a/_includes/_root/n-queens-ii/Solution.java +++ /dev/null @@ -1,58 +0,0 @@ -public class Solution { - - boolean[][] chessboard; - - int target; - - int rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - rt++; - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public int totalNQueens(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - chessboard = new boolean[n][n]; - target = n - 1; - - rt = 0; - - search(0); - - return rt; - } -} \ No newline at end of file diff --git a/_includes/_root/n-queens/README.md b/_includes/_root/n-queens/README.md deleted file mode 100644 index 8649a85..0000000 --- a/_includes/_root/n-queens/README.md +++ /dev/null @@ -1,92 +0,0 @@ -## My old days - -[Eight-Queens](http://en.wikipedia.org/wiki/Eight_queens_puzzle) is the first advanced problem I can solve. 'Advanced' here means that I can only solve problems like `counting words` at that time. - -Thanks to [USACO](http://cerberus.delos.com:791/usacogate). More than ten years had passed, I can clearly remember the last answer of `Eight-Queens`, `84136275`. - - -## [Depth-first search](http://en.wikipedia.org/wiki/Depth-first_search) and [Backtracking](http://en.wikipedia.org/wiki/Backtracking) - -DFS is a brute force method, and has a common pattern. - -Pattern for problems with many steps and each step has many choices: - - -``` - -selected_choices stores [step_0 : choice_x, step1: choice_y, ...] - -dfs(step) - - if all steps had theirs choice - selected_choices is an answer - - foreah choice in all choices in current step - - if choice is possiable - - selected_choices[step] = choice - - dfs(next step) - - // this is called backtracking - selected_choices[step] = no choice yet or last choice - -``` - -### Apply the pattern to n-Queens - -put the queen on the `n * n` chessboard. - - * `steps`: n rows - * `choices each step`: n grid on current row - * `possibility checker` : the choosen grid is not sharing same column or diagonal. (the current row has only choosen grid, no need to check) - - -fake board - -``` -a boolean[n][n] array to simulate a chessboard - -chessboard[row][column] = true is for putting a queen -``` - - -possibility checker function: - - -``` -function check_can_put(row, col) - - if queen on same column - return false - - if queen on same diagonal - return false - -``` - -DFS function - -``` -function N_queen(row) - - if row > N - convert chessboard into result - - - foreah col in current row - - if check_can_put(row, col) - - // put queen - chessboard[row][col] = true - - N_queen(row + 1) - - // take queen away - chessboard[row][col] = false - -``` - - diff --git a/_includes/_root/n-queens/Solution.java b/_includes/_root/n-queens/Solution.java deleted file mode 100644 index 7f28524..0000000 --- a/_includes/_root/n-queens/Solution.java +++ /dev/null @@ -1,67 +0,0 @@ -public class Solution { - boolean[][] chessboard; - - int target; - - ArrayList rt; - - boolean tryput(final int row, final int col){ - for(int i = row - 1; i >= 0; i--){ - int offset = row - i; - if(chessboard[i][col]) - return false; - - if(col - offset >= 0 && chessboard[i][col - offset]) - return false; - - if(col + offset <= target && chessboard[i][col + offset]) - return false; - } - - return true; - } - - void search(final int row){ - - if( row > target){ - - String[] valid = new String[target + 1]; - - for(int i = 0; i <= target ; i++){ - char[] s = new char[target + 1]; - for(int j = 0; j <= target; j++){ - s[j] = chessboard[i][j] ? 'Q' : '.'; - } - - valid[i] = new String(s); - } - - rt.add(valid); - - return; - } - - for(int i = 0; i <= target ; i++){ - if(tryput(row, i)){ - - chessboard[row][i] = true; - - search(row + 1); - - chessboard[row][i] = false; - } - } - - } - - public List solveNQueens(int n) { - chessboard = new boolean[n][n]; - target = n - 1; - - rt = new ArrayList(); - - search(0); - - return rt; - } -} diff --git a/_includes/_root/next-permutation/README.md b/_includes/_root/next-permutation/README.md deleted file mode 100644 index b4b77cc..0000000 --- a/_includes/_root/next-permutation/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## [Generation in lexicographic order](http://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order) - -I can not work out this without Google's help. - -steps below are copied from Wikipedia: - - 1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. - 1. Find the largest index l greater than k such that a[k] < a[l]. - 1. Swap the value of a[k] with that of a[l]. - 1. Reverse the sequence from a[k + 1] up to and including the final element a[n]. - - -[Fisherlei's Image](http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html) is a good illustration. -You can see an image that how this solution goes. diff --git a/_includes/_root/next-permutation/Solution.java b/_includes/_root/next-permutation/Solution.java deleted file mode 100644 index e0166e2..0000000 --- a/_includes/_root/next-permutation/Solution.java +++ /dev/null @@ -1,39 +0,0 @@ -public class Solution { - // http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public void nextPermutation(int[] num) { - - if(num.length < 2) return; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - } -} \ No newline at end of file diff --git a/_includes/_root/one-edit-distance/README.md b/_includes/_root/one-edit-distance/README.md deleted file mode 100644 index 2c95d72..0000000 --- a/_includes/_root/one-edit-distance/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## [Edit Distance](../edit-distance) == 1 - -My first submission - - -``` -return minDistance(s, t) == 1; -``` - -but, leetcode shows `time limit exceeded`. - - -## Only 1 diff - -### Same length - -do one pass can know if there is only one different char - -### 1 char longer - -delete the redundant char will yield two same string - -Note: - -solved in `O(n)`. [Edit Distance](../edit-distance) == 1 is an `O(n * n)` solution. - diff --git a/_includes/_root/one-edit-distance/Solution.java b/_includes/_root/one-edit-distance/Solution.java deleted file mode 100644 index b9ac735..0000000 --- a/_includes/_root/one-edit-distance/Solution.java +++ /dev/null @@ -1,37 +0,0 @@ -public class Solution { - public boolean isOneEditDistance(String s, String t) { - - char[] S = s.toCharArray(); - char[] T = t.toCharArray(); - - // make sure s is always to shorter one - if (S.length > T.length) return isOneEditDistance(t, s); - - if (T.length - S.length > 1) return false; - - int diff = 0; - - int i = 0; - int j = 0; - - for(/* void */; i < S.length; i++, j++){ - if(S[i] != T[j]){ - - diff++; - - if(diff > 1) return false; - - // len(s) + 1 = len(t) - if(S.length != T.length && S[i] == T[j + 1]){ - j++; // delete one from T - } - } - } - - if (diff == 0){ - return j + 1 == T.length; - } - - return j == T.length; - } -} diff --git a/_includes/_root/palindrome-number/README.md b/_includes/_root/palindrome-number/README.md deleted file mode 100644 index 8b266e0..0000000 --- a/_includes/_root/palindrome-number/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## Number version [Valid Palindrome](../valid-palindrome) - -unlike string, we can't use an pointer to access the `i`th of a number. - -mathematical method to extract `i`th of the number `x` - -``` -function ith(x, i) - return (x / Math.pow(10, i)) % 10 -``` diff --git a/_includes/_root/palindrome-number/Solution.java b/_includes/_root/palindrome-number/Solution.java deleted file mode 100644 index 8578bb7..0000000 --- a/_includes/_root/palindrome-number/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -public class Solution { - public boolean isPalindrome(int x) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - - if(x < 0) return false; - - if(x == 0) return true; - - int size = (int)Math.log10(x); - - int mid = size / 2; - - for(int i = 0; i <= mid; i++){ - - int p = (int) (x / Math.pow(10, i)) % 10; - int q = (int) (x / Math.pow(10, size - i)) % 10; - if(p != q) - return false; - - } - - return true; - } -} \ No newline at end of file diff --git a/_includes/_root/palindrome-partitioning-ii/README.md b/_includes/_root/palindrome-partitioning-ii/README.md deleted file mode 100644 index 17ce3cf..0000000 --- a/_includes/_root/palindrome-partitioning-ii/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## [Longest Palindromic Substring](../longest-palindromic-substring) + [Word Break](../word-break) - -After running [Longest Palindromic Substring](../longest-palindromic-substring), -we got a table `P[len][index]`, that is, we can tell if `s[i..j]` is palindromic - -## Apply [Word Break](../word-break) - -`M[i]` means the mincut of `s[0..i]`. - -When a new char comes, we have 3 choices: - - * `M[i + 1] = 0`: if `s[0..i + 1]` is palindromic - * `M[i + 1] = M[i] + 1`: cut at `i`, between the old string `s[0..i]` and the new char. - * `M[i + 1] = M[j] + 1`: cut at `j`, `j from 0 -> i`, such that `s[j..i+1]` is palindromic, between the `s[0..j]` and `s[j..i + 1]`. - -Our job is to find the minimum value among them. diff --git a/_includes/_root/palindrome-partitioning-ii/Solution.java b/_includes/_root/palindrome-partitioning-ii/Solution.java deleted file mode 100644 index d34fffd..0000000 --- a/_includes/_root/palindrome-partitioning-ii/Solution.java +++ /dev/null @@ -1,49 +0,0 @@ -public class Solution { - public int minCut(String s) { - char[] S = s.toCharArray(); - - if(S.length == 0) return 0; - - boolean[][] P = new boolean[S.length][S.length]; - - // len 1 - Arrays.fill(P[1 - 1], true); - - // len 2 - for(int i = 0; i < S.length - 1; i++){ - P[2 - 1][i] = S[i] == S[i + 2 - 1]; - } - - // len 3 to max - for(int len = 3; len <= S.length; len++){ - - for(int i = 0; i < S.length - (len - 1); i++){ - P[len - 1][i] = P[len - 1 - 2][i + 1] && S[i] == S[i + len - 1]; - } - } - - int[] mincut = new int[S.length + 1]; - - mincut[0] = 0; - mincut[1] = 0; - - for(int len = 2; len <= S.length; len++){ - - if(P[len - 1][0]){ - mincut[len] = 0; - }else{ - - mincut[len] = mincut[len - 1] + 1; - - for(int i = 1; i < len - 1; i++){ - - if(P[len - i - 1][i]){ - mincut[len] = Math.min(mincut[i] + 1 , mincut[len]); - } - } - } - } - - return mincut[S.length]; - } -} diff --git a/_includes/_root/palindrome-partitioning/README.md b/_includes/_root/palindrome-partitioning/README.md deleted file mode 100644 index ee88ab8..0000000 --- a/_includes/_root/palindrome-partitioning/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Recursion - -``` -i = 0 .. end - -partition(s) = s[0..i] + partition(s[i+1 .. end]) if s[0..i] is palindromic - -``` - diff --git a/_includes/_root/palindrome-partitioning/Solution.java b/_includes/_root/palindrome-partitioning/Solution.java deleted file mode 100644 index db94c57..0000000 --- a/_includes/_root/palindrome-partitioning/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -public class Solution { - - boolean isPal(String s){ - - char[] S = s.toCharArray(); - - for(int i = 0; i < S.length / 2; i++){ - if(S[i] != S[S.length - i - 1]) - return false; - } - - return true; - } - - - - public List> partition(String s) { - - List> rt = new ArrayList>(); - - if("".equals(s)) return rt; - if(s.length() == 1) return Arrays.asList(Arrays.asList(s)); - - for(int i = 0; i < s.length(); i++){ - String x = s.substring(0, i + 1); - if(isPal(x)){ - List> sub = partition(s.substring(i + 1)); - - if(sub.isEmpty()){ - rt.add(Arrays.asList(x)); - } else { - for(List l : sub){ - ArrayList _l = new ArrayList(); - _l.add(x); - _l.addAll(l); - rt.add(_l); - } - } - } - } - - return rt; - - } -} \ No newline at end of file diff --git a/_includes/_root/partition-list/README.md b/_includes/_root/partition-list/README.md deleted file mode 100644 index 5883786..0000000 --- a/_includes/_root/partition-list/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Secret of QuickSort - -This is the core technology of QuickSort. - -The `x` here is the `pivot`. Create two linked list head, one is for nodes less than the `pivot`, the other is for node greater than or equals to the `pivot`. - -After all nodes are sent into the two heads, join the two heads togetoher. - diff --git a/_includes/_root/partition-list/Solution.java b/_includes/_root/partition-list/Solution.java deleted file mode 100644 index 4580a4b..0000000 --- a/_includes/_root/partition-list/Solution.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode partition(ListNode head, int x) { - if(head == null) return null; - if(head.next == null) return head; - - final ListNode less = new ListNode(0); - final ListNode greater = new ListNode(0); - - ListNode _less = less; - ListNode _greater = greater; - - while(head != null){ - ListNode t = head; - head = head.next; - - if(t.val < x){ - _less.next = t; - _less = _less.next; - }else { - _greater.next = t; - _greater = _greater.next; - } - } - - _greater.next = null; - - _less.next = greater.next; - - return less.next; - - } -} diff --git a/_includes/_root/pascals-triangle-ii/README.md b/_includes/_root/pascals-triangle-ii/README.md deleted file mode 100644 index 95d08a3..0000000 --- a/_includes/_root/pascals-triangle-ii/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Easier than [Pascal's Triangle I](../pascals-triangle) - -Output `row[i]` only diff --git a/_includes/_root/pascals-triangle-ii/Solution.java b/_includes/_root/pascals-triangle-ii/Solution.java deleted file mode 100644 index dd8a4ba..0000000 --- a/_includes/_root/pascals-triangle-ii/Solution.java +++ /dev/null @@ -1,15 +0,0 @@ -public class Solution { - public List getRow(int rowIndex) { - Integer[] row = new Integer[rowIndex + 1]; - - Arrays.fill(row, 1); - - for(int i = 0 ; i < rowIndex - 1; i++){ - for(int j = i + 1; j >= 1; j--){ - row[j] = row[j] + row[j - 1]; - } - } - - return Arrays.asList(row); - } -} diff --git a/_includes/_root/pascals-triangle/README.md b/_includes/_root/pascals-triangle/README.md deleted file mode 100644 index 124d559..0000000 --- a/_includes/_root/pascals-triangle/README.md +++ /dev/null @@ -1,22 +0,0 @@ -## Recursion - -from the definition, it is easy to know - -``` - - [1], - [1,1], - [1,2,1], - [1,3,3,1], - [1,4,6,4,1] - - 0 1 2 3 4 - - -//i start from 0 -row[0] = 1 -row[last] = 1 - -row[i] = prev_row[i] + prev_row[i - 1] - -``` diff --git a/_includes/_root/pascals-triangle/Solution.java b/_includes/_root/pascals-triangle/Solution.java deleted file mode 100644 index 503e03d..0000000 --- a/_includes/_root/pascals-triangle/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -public class Solution { - public List> generate(int numRows) { - - ArrayList> rt = new ArrayList>(); - - Integer[] prev = null; - - for(int i = 1 ; i <= numRows; i++){ - - Integer[] row = new Integer[i]; - - row[0] = 1; - row[i - 1] = 1; - - for(int j = 1; j < i - 1 ; j++){ - //row.add(j, prev.get(j) + prev.get(j -1)); - row[j] = prev[j] + prev[j - 1]; - } - - rt.add(new ArrayList(Arrays.asList(row))); - prev = row; - } - - - return rt; - - } -} diff --git a/_includes/_root/path-sum-ii/README.md b/_includes/_root/path-sum-ii/README.md deleted file mode 100644 index ecf07e6..0000000 --- a/_includes/_root/path-sum-ii/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Definition - -Similar to [Sum Root to Leaf Numbers](../sum-root-to-leaf-numbers) - - -``` -pathSum(node) = [] [ empty tree ] - parent_list(node) union node.val [ node is leaf ] - pathSum(node.left) unoin pathSum(node.right) [ otherwise ] - -parent_list(node) = [] [ node is root ] - parent_list(parent_node) union parent_node.val [ otherwise ] -``` - - - diff --git a/_includes/_root/path-sum-ii/Solution.java b/_includes/_root/path-sum-ii/Solution.java deleted file mode 100644 index ab9ab8a..0000000 --- a/_includes/_root/path-sum-ii/Solution.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - void addIfNotEmpty(List> rt, List> l){ - if(!l.isEmpty()){ - rt.addAll(l); - } - } - - List> pathSum(TreeNode root, int sum, List parents) { - List> rt = new ArrayList>(); - - if(root == null) return rt; - - ArrayList p = new ArrayList(parents); - p.add(root.val); - - if(root.left == null & root.right == null){ - if(root.val == sum){ - rt.add(p); - } - - return rt; - } - - addIfNotEmpty(rt, pathSum(root.left, sum - root.val, p)); - addIfNotEmpty(rt, pathSum(root.right, sum - root.val, p)); - - return rt; - } - - public List> pathSum(TreeNode root, int sum) { - - return pathSum(root, sum, new ArrayList()); - } -} diff --git a/_includes/_root/path-sum/README.md b/_includes/_root/path-sum/README.md deleted file mode 100644 index 7038323..0000000 --- a/_includes/_root/path-sum/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Recursion - - * Empty tree has no path sum - * A leaf node has path sum only if its value equals to the sum value - * A node with children node could have a path sum when one/all of its children has a path sum `sum - node.value` . diff --git a/_includes/_root/path-sum/Solution.java b/_includes/_root/path-sum/Solution.java deleted file mode 100644 index 02715bf..0000000 --- a/_includes/_root/path-sum/Solution.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - - - public boolean hasPathSum(TreeNode root, int sum) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (root == null) - return false; - - if (root.left == null && root.right == null) //leaf - return root.val == sum; - - return (root.left != null && hasPathSum(root.left, sum - root.val)) - || (root.right != null && hasPathSum(root.right, sum - root.val)); - } -} \ No newline at end of file diff --git a/_includes/_root/permutation-sequence/README.md b/_includes/_root/permutation-sequence/README.md deleted file mode 100644 index aeec43f..0000000 --- a/_includes/_root/permutation-sequence/README.md +++ /dev/null @@ -1,132 +0,0 @@ -## [Factorial number system](http://en.wikipedia.org/wiki/Factorial_number_system#Permutations) - -It has to master this technology to find `kth` permutation or time limited. - -## Detail steps - -using wikipedia example - -2982th permutation of `[1, 2, 3, 4, 5, 6, 7]`. - -### Convert `k` to factorial based number - -``` -k = 2982 -n = 7 -``` - -start form `n - 1` - -``` -2982 / 6! = 4 and remainder 102 | 4 -102 / 5! = 0 and remainder 102 | 0 -102 / 4! = 4 and remainder 6 | 4 -6 / 3! = 1 and remainder 0 | 1 -0 / 2! = 0 and remainder 0 | 0 -0 / 1! = 0 and remainder 0 | 0 -0 / 0! = 0 and remainder 0 | 0 -``` - -So, `2982(10base) = 4041000(!base)` - -### Recover factorial based number to permutation. - -``` - - - -index: 0 1 2 3 4 5 6 -chars: [1, 2, 3, 4, 5, 6, 7] -final: [] - - -number: 4041000 - ^ - | - -Move chars[4] to the end of final - - -chars: [1, 2, 3, 4, 5, 6, 7] BEFORE -index: 0 1 2 3 4 5, 6 -final: [5] -chars: [1, 2, 3, 4, 6, 7] AFTER - - -number: 4041000 - ^ - | - -Move chars[0] to the end of final - -chars: [1, 2, 3, 4, 6, 7] BEFORE -index: 0 1 2 3 4 5 -final: [5, 1] -chars: [2, 3, 4, 6, 7] AFTER - -number: 4041000 - ^ - | - -Move chars[4] to the end of final - -chars: [2, 3, 4, 6, 7] BEFORE -index: 0 1 2 3 4 -final: [5, 1, 7] -chars: [2, 3, 4, 6] AFTER - - - -number: 4041000 - ^ - | - -Move chars[1] to the end of final - -chars: [2, 3, 4, 6] BEFORE -index: 0 1 2 3 -final: [5, 1, 7, 3] -chars: [2, 4, 6] AFTER - - - -number: 4041000 - ^ - | - -Move chars[0] to the end of final - -chars: [2, 4, 6] BEFORE -index: 0 1 2 -final: [5, 1, 7, 3, 2] -chars: [4, 6] AFTER - - - -number: 4041000 - ^ - | - -Move chars[0] to the end of final - -chars: [4, 6] BEFORE -index: 0 1 -final: [5, 1, 7, 3, 2, 4] -chars: [6] AFTER - - -number: 4041000 - ^ - | - -Move chars[0] to the end of final - -chars: [6] BEFORE -index: 0 -final: [5, 1, 7, 3, 2, 4, 6] -chars: [] AFTER - - -``` - -The 2982th permutation of `[1, 2, 3, 4, 5, 6, 7]` is `[5, 1, 7, 3, 2, 4, 6]` diff --git a/_includes/_root/permutation-sequence/Solution.java b/_includes/_root/permutation-sequence/Solution.java deleted file mode 100644 index ce7abe3..0000000 --- a/_includes/_root/permutation-sequence/Solution.java +++ /dev/null @@ -1,40 +0,0 @@ -public class Solution { - - int fact(int x){ - int s = 1; - - for(int i = 1; i <= x; i++) - s *= i; - - return s; - } - - public String getPermutation(int n, int k) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ArrayList chars = new ArrayList(); - - for(int i = '1'; i <('1' + n); i++) - chars.add((char)i); - - k -= 1; - - char[] t = new char[n]; - int l = 0; - - for(int i = n - 1; i > 0; i--){ - int f = fact(i); - - int c = k / f; - - t[l++] = chars.get(c); - chars.remove(c); - - k %= f; - } - - t[n - 1] = chars.get(0); - - return new String(t); - - } -} \ No newline at end of file diff --git a/_includes/_root/permutations-ii/README.md b/_includes/_root/permutations-ii/README.md deleted file mode 100644 index e7586bf..0000000 --- a/_includes/_root/permutations-ii/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Variant of [Next Permutation](../next-permutation) - -With the help of [Next Permutation](../next-permutation), you can find all unique permutations from the first permutation. - -### First and Last - - * First permutation is the numbers in non-descending order - * Last permutation is the numbers in non-ascending order - - -so the code is like - -``` -sort(num) // make it the first - - -while num is not the last - call nextPermutation(num) - - copy num into result - - -``` diff --git a/_includes/_root/permutations-ii/Solution.java b/_includes/_root/permutations-ii/Solution.java deleted file mode 100644 index a0d2b4c..0000000 --- a/_includes/_root/permutations-ii/Solution.java +++ /dev/null @@ -1,61 +0,0 @@ -public class Solution { - - void swap(int x[], int a, int b) { - int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - public boolean nextPermutation(int[] num) { - - if(num.length < 2) return false; - - int p = -1; - - for(int i = num.length - 1; i >0; i--){ - if(num[i] > num[i - 1]){ - p = i - 1; - break; - } - } - - if(p == -1){ - Arrays.sort(num); - return false; - } - - int c = -1; - for(int i = num.length - 1; i >=0; i--){ - if(num[i] > num[p]) { - c = i; - break; - } - } - - swap(num, p, c); - Arrays.sort(num, p + 1, num.length); - - return true; - } - - List asList(int[] num){ - ArrayList l = new ArrayList(num.length); - for(int i = 0; i < num.length; i++) - l.add(num[i]); - - return l; - } - - public List> permuteUnique(int[] num) { - Arrays.sort(num); - - ArrayList> found = new ArrayList>(); - found.add(asList(num)); - - while(nextPermutation(num)){ - found.add(asList(num)); - } - - return found; - } -} diff --git a/_includes/_root/permutations/README.md b/_includes/_root/permutations/README.md deleted file mode 100644 index 2796a26..0000000 --- a/_includes/_root/permutations/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Definition - - -``` - -permute(num) = empty num is empty - num num has only one element - n + permute(num - n) [n in num] otherwise - -``` - - - diff --git a/_includes/_root/permutations/Solution.java b/_includes/_root/permutations/Solution.java deleted file mode 100644 index a1e1ae7..0000000 --- a/_includes/_root/permutations/Solution.java +++ /dev/null @@ -1,35 +0,0 @@ -public class Solution { - - int[] resetof(int[] num, int index){ - int[] rt = new int[num.length - 1]; - int s = 0; - for(int i = 0; i < num.length ; i++) - if(i != index) rt[s++] = num[i]; - - return rt; - } - - public List> permute(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if(num.length == 0){ - // do nothing - }else if(num.length == 1) { - rt.add(new ArrayList(Arrays.asList(num[0]))); - }else{ - - for(int i = 0; i < num.length; i++){ - for(List l : permute(resetof(num, i))){ - l.add(num[i]); - rt.add(l); - }; - } - - } - - return rt; - - - } -} diff --git a/_includes/_root/plus-one/README.md b/_includes/_root/plus-one/README.md deleted file mode 100644 index 99288da..0000000 --- a/_includes/_root/plus-one/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Deal with [carry](http://en.wikipedia.org/wiki/Carry_(arithmetic)) - -The bad news after the add one to digits is resulting a carry. - -when there is a carry, `digit[i]` should transfer `digit[i] / 10` to its left digit (`digit[i -1]`). -`digit[i]` will be `digit[i] % 10` after transfering. - -So, our work is to start from right most digit and make sure each digit is the right value. - - -``` -foreach index from right most to left most in digits - - // transfer - digits[i - 1] = digits[i - 1] + digits[i] / 10 - - digits[i] = digits[i] % 10 - -``` - -Sometimes, the left more digit will too result a carry, so make sure there is enough space to put the new transfered digit. diff --git a/_includes/_root/plus-one/Solution.java b/_includes/_root/plus-one/Solution.java deleted file mode 100644 index e31cd2c..0000000 --- a/_includes/_root/plus-one/Solution.java +++ /dev/null @@ -1,17 +0,0 @@ -public class Solution { - public int[] plusOne(int[] digits) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - int[] result = new int[digits.length + 1]; - digits[digits.length - 1] += 1; - for(int i = digits.length - 1; i >=0 ; i--){ - result[ i + 1 ] += digits[i]; - result[ i ] += result[ i + 1 ] / 10; - result[ i + 1 ] %= 10; - } - - if(result[0] == 0) return Arrays.copyOfRange(result, 1 , result.length); - else - return result; - } -} \ No newline at end of file diff --git a/_includes/_root/populating-next-right-pointers-in-each-node-ii/README.md b/_includes/_root/populating-next-right-pointers-in-each-node-ii/README.md deleted file mode 100644 index dad68e8..0000000 --- a/_includes/_root/populating-next-right-pointers-in-each-node-ii/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## Improved version of [Populating Next Right Pointers in Each Node](../populating-next-right-pointers-in-each-node) - -This time, finding next is a bit difficult. -`node.right.next = node.next.left` is no longer working. - -But parent's next is also useful, and only need to seach a little more nodes. - -``` - 1 - / \ - 2 3 - \ \ - 4 5 - / / \ - 6 7 8 -``` - - * `6.next` = `7` = `5.left` = `4.next.left` - * `4.next` = `5` = `3.right` = `2.next.right` - -Searching path is like - - * node's parent's left - * node's parent's right - * take node's parent's next as parent and search again - - -Note: - -`connect(right)` before `connect(left)`, because `left nodes` depend on `right nodes' next` diff --git a/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java b/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java deleted file mode 100644 index a470db6..0000000 --- a/_includes/_root/populating-next-right-pointers-in-each-node-ii/Solution.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeLinkNode ORPHAN = new TreeLinkNode(0); - - TreeLinkNode sib(TreeLinkNode me, TreeLinkNode parent){ - - if(parent == null) return null; - - if(parent.left != null && parent.left != me){ - return parent.left; - } - - if(parent.right != null){ - return parent.right; - } - - return sib(ORPHAN, parent.next); - - } - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - if(root.left != null){ - root.left.next = sib(root.left, root); - } - - - if(root.right != null){ - root.right.next = sib(ORPHAN, root.next); - } - - connect(root.right); - connect(root.left); - - - } -} \ No newline at end of file diff --git a/_includes/_root/populating-next-right-pointers-in-each-node/README.md b/_includes/_root/populating-next-right-pointers-in-each-node/README.md deleted file mode 100644 index d010505..0000000 --- a/_includes/_root/populating-next-right-pointers-in-each-node/README.md +++ /dev/null @@ -1,38 +0,0 @@ -## First glance - -It would be an easy problem if [Binary Tree Level Order Traversal](../binary-tree-level-order-traversal) works. -Yet, a queue is not allow because of that constant space is required. - -## Recursion - -connecting left and right child is easy, just `node.left.next = node.right` - - -Before - -``` - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 -``` - - -After - -``` - 1 - / \ - 2 -> 3 - / \ / \ - 4-> 5 6->7 -``` - -`5` and `6` shoud be connected。 - -when connecting `4` and `5`, `2` and `3` is already connected, that is a good news, we can connect `5` and `6` using `2.next`. - -``` -node.right.next = node.next.left; -``` diff --git a/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java b/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java deleted file mode 100644 index 7dcfb82..0000000 --- a/_includes/_root/populating-next-right-pointers-in-each-node/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Definition for binary tree with next pointer. - * public class TreeLinkNode { - * int val; - * TreeLinkNode left, right, next; - * TreeLinkNode(int x) { val = x; } - * } - */ -public class Solution { - - - public void connect(TreeLinkNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null || root.left == null || root.right == null) return; - - root.left.next = root.right; - - if(root.next != null){ - root.right.next = root.next.left; - } - - connect(root.left); - connect(root.right); - - } -} \ No newline at end of file diff --git a/_includes/_root/powx-n/README.md b/_includes/_root/powx-n/README.md deleted file mode 100644 index 7fa3fac..0000000 --- a/_includes/_root/powx-n/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Make Pow(x, n) lg(n) - -`lg(n)` is telling us just `/2`. - -`Pow(x, n) = Pow(x, n / 2) * Pow(x, n / 2)` - -so, if we remember the result of `Pow(x, n / 2)`, we can save up half of the cost. - - diff --git a/_includes/_root/powx-n/Solution.java b/_includes/_root/powx-n/Solution.java deleted file mode 100644 index f8e8026..0000000 --- a/_includes/_root/powx-n/Solution.java +++ /dev/null @@ -1,17 +0,0 @@ -public class Solution { - public double pow(double x, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(n == 0) return 1; - - double s = pow(x, n /2); - - if(n % 2 == 0) - return s * s; - else if(n > 0) - return s * s * x; - else - return s * s / x; - - - } -} diff --git a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md deleted file mode 100644 index 81e0be1..0000000 --- a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## EAGAIN and read - -This is a common problem in real world. -when client read some data from server, data will not always be available to be read. -`read` might return an error like `EAGAIN` in order to tell client that you can do something else now, -call me later. - -## difference from [Read N Characters Given Read4](../read-n-characters-given-read4) - -when you call `read4`, it might return 4 `char`s. -however, the `read` only ask you for 1 `char`. -you cannot throw the 3 `char`s away, because `read` may ask you for that 3 `char` when next call. - -to solve this, just to add a `localbuff` to store all `char` got from `read4`, and send them one by one to `read`. - -``` - | just store these two chars for coming read call - V - .... .... .... ..** .... .. -[++++ ++++ ++++ ++][ ++++ +] - -``` - diff --git a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/Solution.java b/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/Solution.java deleted file mode 100644 index 35d2eb1..0000000 --- a/_includes/_root/read-n-characters-given-read4-ii-call-multiple-times/Solution.java +++ /dev/null @@ -1,37 +0,0 @@ -/* The read4 API is defined in the parent class Reader4. -int read4(char[] buf); */ - -public class Solution extends Reader4 { - - LinkedList queue = new LinkedList(); - - /** - * @param buf Destination buffer - * @param n Maximum number of characters to read - * @return The number of characters read - */ - public int read(char[] buf, int n) { - - char[] _buf = new char[4]; - - int total = 0; - - while(true){ - int l = read4(_buf); - - for(int i = 0; i < l; i++){ - queue.add(_buf[i]); - } - - l = Math.min(n - total, queue.size()); - - for(int i = 0; i < l; i++){ - buf[total++] = queue.poll(); - } - - if(l == 0) break; - } - - return total; - } -} diff --git a/_includes/_root/read-n-characters-given-read4/README.md b/_includes/_root/read-n-characters-given-read4/README.md deleted file mode 100644 index 40f4900..0000000 --- a/_includes/_root/read-n-characters-given-read4/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Forward to `read`'s `buf` until `read4` reach its end or `read`'s `buf` full - - -``` -.... .... .... ...E <- data read4 -++++ ++++ ++++ ++ <- data pipe to read -``` - -code should be like below - -``` -while not EOF or buf not full - append read4 to buf -``` diff --git a/_includes/_root/read-n-characters-given-read4/Solution.java b/_includes/_root/read-n-characters-given-read4/Solution.java deleted file mode 100644 index 4bc3197..0000000 --- a/_includes/_root/read-n-characters-given-read4/Solution.java +++ /dev/null @@ -1,31 +0,0 @@ -/* The read4 API is defined in the parent class Reader4. -int read4(char[] buf); */ - -public class Solution extends Reader4 { - /** - * @param buf Destination buffer - * @param n Maximum number of characters to read - * @return The number of characters read - */ - public int read(char[] buf, int n) { - - char[] _buf = new char[4]; - - int total = 0; - - while(true){ - int l = read4(_buf); - - if(l == 0) break; - - l = Math.min(n - total, l); - - for(int i = 0; i < l; i++){ - buf[total++] = _buf[i]; - } - - } - - return total; - } -} diff --git a/_includes/_root/recover-binary-search-tree/README.md b/_includes/_root/recover-binary-search-tree/README.md deleted file mode 100644 index 318ca83..0000000 --- a/_includes/_root/recover-binary-search-tree/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Which two are swapped by mistake - -a BST should yield an array of number in non-descending order. - -Inorder travel the tree will find out which two are bad. diff --git a/_includes/_root/recover-binary-search-tree/Solution.java b/_includes/_root/recover-binary-search-tree/Solution.java deleted file mode 100644 index f3813ec..0000000 --- a/_includes/_root/recover-binary-search-tree/Solution.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - TreeNode[] bad; - TreeNode last; - - - void inorder(TreeNode root){ - - if(root.left != null) inorder(root.left); - - if(last != null && last.val > root.val){ // - bad[0] = root; - - if(bad[1] == null) bad[1] = last; - } - - last = root; - - - if(root.right != null) inorder(root.right); - - } - - public void recoverTree(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(root == null) return; - - bad = new TreeNode[2]; - bad[0] = null; - bad[1] = null; - last = null; - - inorder(root); - - - if(bad[0] != null && bad[1] != null){ - int t = bad[0].val; - bad[0].val = bad[1].val; - bad[1].val = t; - } - - - } -} \ No newline at end of file diff --git a/_includes/_root/regular-expression-matching/README.md b/_includes/_root/regular-expression-matching/README.md deleted file mode 100644 index aede44e..0000000 --- a/_includes/_root/regular-expression-matching/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Finite-State Automaton - - * [Convert Regular Expression to Finite-State Automaton 1](https://www.youtube.com/watch?v=GwsU2LPs85U) - * [Convert Regular Expression to Finite-State Automaton 2](https://www.youtube.com/watch?v=shN_kHBFOUE) - * [Regular Expression to NFA](https://www.youtube.com/watch?v=RYNN-tb9WxI) - * [Convert NFA to DFA](https://www.youtube.com/watch?v=taClnxU-nao) - - -I learnt `Finite-State Automaton` many years ago. This problem is a good chance for me to make one myself. -Maybe there are many other ways to solve this problem since it is a simple regex matching. -However, this problem helps me understand `Finite-State Automaton` better. - -Code shoud do as following - - - 1. Build a [NFA](http://en.wikipedia.org/wiki/Nondeterministic_finite_automaton_with_%CE%B5-moves) using pattern - 1. Convert to [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton) - 1. Let string walk in the DFA to see if it matches the pattern - - - diff --git a/_includes/_root/regular-expression-matching/Solution.java b/_includes/_root/regular-expression-matching/Solution.java deleted file mode 100644 index 3140552..0000000 --- a/_includes/_root/regular-expression-matching/Solution.java +++ /dev/null @@ -1,232 +0,0 @@ -public class Solution { - static final Character EPSILON = 0; - - static class State{ - - static Set allchar = new HashSet(); - - boolean end; - - Map> next = new HashMap>(); - - State(){ - this(false); - } - - State(boolean end){ - this.end = end; - } - - State match(Character c) { - Set states = next.get(c); - - if(states == null){ - states = next.get('.'); - } - - if(states != null) { - for (State s : states) { - return s; - } - } - - return null; - } - - Set matchAll(Character c) { - Set match = next.get(c); - - return match; - } - - void addNext(Character c, State s){ - - if(c != EPSILON) - allchar.add(c); - - Set l = next.get(c); - - if(l == null){ - l = new HashSet(); - next.put(c, l); - } - - l.add(s); - } - } - - State nfa(char[] pattern){ - - final State end = new State(true); - - State last = end; - - for(int i = pattern.length - 1; i >= 0; i--){ - if(pattern[i] == '*'){ - i--; - - State s1 = new State(); - State s2 = new State(); - State s3 = new State(); - State s4 = last; - - s1.addNext(EPSILON, s2); - s1.addNext(EPSILON, s4); - - s2.addNext(pattern[i], s3); - - s3.addNext(EPSILON, s4); - - s4.addNext(EPSILON, s2); - - last = s1; - - }else{ - State curr = new State(); - curr.addNext(pattern[i], last); - last = curr; - } - } - - - return last; - } - - boolean end(Set states){ - for (State state : states) { - if(state.end){ - return true; - } - } - return false; - } - - State dfa(State start){ - - Map, HashMap>> table = new HashMap, HashMap>>(); - Map, State> toone = new HashMap, State>(); - - final Set enter = allEpslilon(Collections.singleton(start)); - - LinkedList> queue = new LinkedList>(); - queue.add(enter); - - while(!queue.isEmpty()){ - - Set key = queue.poll(); - - if(!toone.containsKey(key)){ - State maps = new State(); - maps.end = end(key); - - toone.put(key, maps); - } - - HashMap> targets = searchTarget(key); - table.put(key, targets); - - for (Set states : targets.values()) { - if(table.get(states) == null){ - queue.add(states); - } - } - - } - - for (Map.Entry, HashMap>> entry : table.entrySet()) { - State s = toone.get(entry.getKey()); - - for (Map.Entry> t : entry.getValue().entrySet()) { - s.addNext(t.getKey(), toone.get(t.getValue())); - } - - } - - return toone.get(enter); - } - - HashMap> searchTarget(Set form) { - HashMap> targets = new HashMap>(); - - for(State s : form) { - for (Character c : State.allchar) { - Set ns = s.matchAll(c); - - if (ns == null) continue; - - Set states = allEpslilon(ns); - - Set t = targets.get(c); - if(t == null){ - t = new HashSet(); - targets.put(c, t); - } - - t.addAll(states); - - } - } - - return targets; - } - - Set allEpslilon(Set ns) { - Set states = new HashSet(); - states.addAll(ns); - - - int oldsize = 0; - - - while (states.size() != oldsize) { - - oldsize = states.size(); - - Set temp = new HashSet(); - - for (State target : states) { - Set t = target.matchAll(EPSILON); - if (t != null) temp.addAll(t); - } - - states.addAll(temp); - - } - return states; - } - - boolean isMatch(char[] s, State state, int p){ - - if(state == null){ - return false; - } - - if(p >= s.length){ - return state.end; - } - - for (Map.Entry> entry : state.next.entrySet()) { - - Character key = entry.getKey(); - if(key.equals(s[p]) || key.equals('.')){ - if(isMatch(s, entry.getValue().iterator().next(), p + 1)){ - return true; - } - } - } - - return false; - } - - public boolean isMatch(String s, String p) { - - State.allchar = new HashSet(); - - State state = nfa(p.toCharArray()); - state = dfa(state); - - char[] chars = s.toCharArray(); - - return isMatch(chars, state, 0); - } -} \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-array-ii/README.md b/_includes/_root/remove-duplicates-from-sorted-array-ii/README.md deleted file mode 100644 index e118121..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-array-ii/README.md +++ /dev/null @@ -1,10 +0,0 @@ -## Improved version of [Remove Duplicates from Sorted Array](../remove-duplicates-from-sorted-array) - -The difference is that how much the wall should be increased. - -if the number is not seen before, the wall should be increased `1` in size. -if the number is seen more than 1 time, the wall should be increased `2` in size. - -As all the numbers are sorted, one variable is enough to count the number ever seen before. - -And the wall should be increased `MIN(lastseencount, 1) + 1` diff --git a/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java b/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java deleted file mode 100644 index 54ca064..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-array-ii/Solution.java +++ /dev/null @@ -1,25 +0,0 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(A.length == 0) return 0; - - int len = 1; - int lastseencount = 0; - - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]){ - - for(int j = i - 1; j > len + Math.min(lastseencount, 1) - 1 ; j--) - A[j] = A[i]; - - len += Math.min(lastseencount, 1) + 1; - lastseencount = 0; - }else{ - lastseencount++; - } - } - - return len + Math.min(lastseencount, 1); - } -} \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-array/README.md b/_includes/_root/remove-duplicates-from-sorted-array/README.md deleted file mode 100644 index 34b32d8..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-array/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## Loop invariant - -If there is `n` joint of different number in the array (`A[i] != A[i - 1]``), -the length of the final array without duplicates should be `n + 1`. - -set a wall -such that the numbers on the left of the wall are unique. - - -if we found a joint, increase the wall and move the unique number onto the left side of the wall. - -``` -[1,1,2] - - w -``` - -joint found, `2 != 1`, move `2` to the left of the wall. - -``` -[1,2,2] - - w -``` - -return wall's length diff --git a/_includes/_root/remove-duplicates-from-sorted-array/Solution.java b/_includes/_root/remove-duplicates-from-sorted-array/Solution.java deleted file mode 100644 index 3edcc3e..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-array/Solution.java +++ /dev/null @@ -1,19 +0,0 @@ -public class Solution { - public int removeDuplicates(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if (A.length == 0) return 0; - - int len = 1; - for(int i = 1; i< A.length; i++){ - if(A[i] != A[i - 1]) { - for(int j = i - 1 ; j > len - 1 ; j-- ) - A[j] = A[i]; - - len++; - } - } - - return len; - } -} \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-list-ii/README.md b/_includes/_root/remove-duplicates-from-sorted-list-ii/README.md deleted file mode 100644 index 46da036..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-list-ii/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Recursion - -take two nodes from the linked list, -if the first's `val` equals to the , we can sure that the first node is unique. -just append `deleteDuplicates(second)` to the first one. - - -if they equals to each other, we can sure that they should be removed. -search through the linked list, remove all nodes until a different one is appeared. diff --git a/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java b/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java deleted file mode 100644 index 06e5fec..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-list-ii/Solution.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head; - - boolean killme = false; - while(node.next != null && node.next.val == v){ - node = node.next; - killme = true; - } - - if(killme) - head = deleteDuplicates(node.next); - else - head.next = deleteDuplicates(node.next); - - return head; - - } -} \ No newline at end of file diff --git a/_includes/_root/remove-duplicates-from-sorted-list/README.md b/_includes/_root/remove-duplicates-from-sorted-list/README.md deleted file mode 100644 index 9caa2f6..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-list/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Loop invariant - -loop the linked list, if the `node.val` equals to the `current.val` ignore it, -append it to the final linked list otherwise. diff --git a/_includes/_root/remove-duplicates-from-sorted-list/Solution.java b/_includes/_root/remove-duplicates-from-sorted-list/Solution.java deleted file mode 100644 index badf567..0000000 --- a/_includes/_root/remove-duplicates-from-sorted-list/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode deleteDuplicates(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return null; - if(head.next == null) return head; - - int v = head.val; - - ListNode node = head.next; - ListNode lasthead = head; - while(node != null){ - - while(node != null && node.val == lasthead.val) node = node.next; - - lasthead.next = node; - lasthead = node; - - if(node != null) node = node.next; - - } - - return head; - } -} \ No newline at end of file diff --git a/_includes/_root/remove-element/README.md b/_includes/_root/remove-element/README.md deleted file mode 100644 index d8746a4..0000000 --- a/_includes/_root/remove-element/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Loop invariant - -Setup a wall, on the left side of the wall are the elements which do not contain the `target`. -When a new element comes and it does not equal to the `target`, enlarge the space on the left side of the wall, and move the new element into the left side of the wall. diff --git a/_includes/_root/remove-element/Solution.java b/_includes/_root/remove-element/Solution.java deleted file mode 100644 index fe31570..0000000 --- a/_includes/_root/remove-element/Solution.java +++ /dev/null @@ -1,16 +0,0 @@ -public class Solution { - public int removeElement(int[] A, int elem) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(A.length == 0) return 0; - - int len = 0; - - for(int i = 0; i< A.length; i++){ - if(A[i] != elem) A[len++] = A[i]; - } - - - return len; - } -} \ No newline at end of file diff --git a/_includes/_root/remove-nth-node-from-end-of-list/README.md b/_includes/_root/remove-nth-node-from-end-of-list/README.md deleted file mode 100644 index b456f9b..0000000 --- a/_includes/_root/remove-nth-node-from-end-of-list/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Nth from end - -Using fast and slow pointers. - -let the faster one runs n step before the slower one, then the slower one starts to run. - -when the faster one meet the end of the linked list, the slower one it pointing to the Nth form the end. diff --git a/_includes/_root/remove-nth-node-from-end-of-list/Solution.java b/_includes/_root/remove-nth-node-from-end-of-list/Solution.java deleted file mode 100644 index 063465a..0000000 --- a/_includes/_root/remove-nth-node-from-end-of-list/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - - final ListNode _head = new ListNode(0); - _head.next = head; - - ListNode fast = _head; - ListNode slow = _head; - - for(int i = 0; i< n ; i++) fast = fast.next; - - while(fast != null && fast.next != null){ - fast = fast.next; - slow = slow.next; - } - - slow.next = slow.next.next; - - return _head.next; - } -} \ No newline at end of file diff --git a/_includes/_root/reorder-list/README.md b/_includes/_root/reorder-list/README.md deleted file mode 100644 index deade0e..0000000 --- a/_includes/_root/reorder-list/README.md +++ /dev/null @@ -1,28 +0,0 @@ -## Sub tasks - -reorder can be achieved via - - 1. cut from the middle into left and right - 1. reverse the right part - 1. join the linked list - -## Some O(n) method to deal with a linked list - -### Reverse a linked list - - 1. walk through the linked list - 1. set `node.next` to `prev` - 1. store `current node` the `prev` - 1. loop - -the initialization of `prev` is the tail `NULL` - -### Finding the middle of a linked list - -fast-slow pointer. - - 1. fast runner goes 2 steps each time - 1. slow runner goes 1 step - 1. when fast reach the end of the linked list, the slow id the middle of the list - - diff --git a/_includes/_root/reorder-list/Solution.java b/_includes/_root/reorder-list/Solution.java deleted file mode 100644 index 547df74..0000000 --- a/_includes/_root/reorder-list/Solution.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - ListNode reverse(ListNode head){ - ListNode prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode mid(ListNode head){ - - ListNode fast = head; - ListNode slow = head; - - while(fast != null && fast.next != null){ - fast = fast.next.next; - slow = slow.next; - } - - return slow; - } - - public void reorderList(ListNode head) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - if(head == null) return; - if(head.next == null) return; - - ListNode left = head; - - ListNode mid = mid(head); - - ListNode right = mid.next; - - if(right == null) return; - - mid.next = null; - - right = reverse(right); - - while(head != null){ - ListNode t = head.next; - - ListNode r = right; - - if(r == null) return; - - head.next = r; - right = right.next; - r.next = t; - - head = t; - } - - } -} \ No newline at end of file diff --git a/_includes/_root/restore-ip-addresses/README.md b/_includes/_root/restore-ip-addresses/README.md deleted file mode 100644 index f27990a..0000000 --- a/_includes/_root/restore-ip-addresses/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Apply DFS pattern - -See DFS pattern in [N-Queens](../n-queens) - - - * `steps`: 4 part of an ip-address - * `choices each step`: 1-3 chars from the string - * `possibility checker`: the number formed by chars should be less than or equals to 255 - -### When to use backtracking - -In this case, I do not use `stack[pstack] = null` after starting to try another choice. - -Because, the value in `stack[pstack]` will not affect any further choice. Rollbacking is not needed and the value will be overwrited. diff --git a/_includes/_root/restore-ip-addresses/Solution.java b/_includes/_root/restore-ip-addresses/Solution.java deleted file mode 100644 index 97f46f4..0000000 --- a/_includes/_root/restore-ip-addresses/Solution.java +++ /dev/null @@ -1,46 +0,0 @@ -public class Solution { - - ArrayList collect; - - String[] stack; - - void findnum(String s, int p, int pstack){ - - if(pstack == 4){ - - if(p >= s.length()){ - String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; - - collect.add(ip); - } - - return; - } - - for(int i = 1; i <= 3; i++){ - - if( p + i > s.length()) - return; - - String number = s.substring(p, p + i); - - if(i > 1 && s.charAt(p) == '0') continue; - - if(Integer.parseInt(number) <= 255){ - stack[pstack] = number; - findnum(s, p + i, pstack + 1); - } - - } - } - - public List restoreIpAddresses(String s) { - - collect = new ArrayList(); - stack = new String[4]; - - findnum(s, 0 , 0); - - return collect; - } -} diff --git a/_includes/_root/reverse-integer/README.md b/_includes/_root/reverse-integer/README.md deleted file mode 100644 index 439bb25..0000000 --- a/_includes/_root/reverse-integer/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Reverse and join - - * convert number into an array of number - * reverse - * create an integer from the reversed array diff --git a/_includes/_root/reverse-integer/Solution.java b/_includes/_root/reverse-integer/Solution.java deleted file mode 100644 index 39688e3..0000000 --- a/_includes/_root/reverse-integer/Solution.java +++ /dev/null @@ -1,24 +0,0 @@ -public class Solution { - public int reverse(int x) { - - if(x == Integer.MIN_VALUE) return 0; - if(x < 0) return -reverse(-x); - - int y = 0; - - do { - - // y * 10 + x % 10 > Integer.MAX_VALUE - if(y > (Integer.MAX_VALUE - x % 10) / 10){ - return 0; - } - - y = y * 10 + x % 10; - - x /= 10; - - } while(x > 0); - - return y; - } -} diff --git a/_includes/_root/reverse-linked-list-ii/README.md b/_includes/_root/reverse-linked-list-ii/README.md deleted file mode 100644 index 57f5af0..0000000 --- a/_includes/_root/reverse-linked-list-ii/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Reverse a linked list - - 1. walk through the linked list - 1. set `node.next` to `prev` - 1. store `current node` the `prev` - 1. loop - -Now, extract the `m` to `n` linked list, reverse it, and join the 3 parts into a new linked list. diff --git a/_includes/_root/reverse-linked-list-ii/Solution.java b/_includes/_root/reverse-linked-list-ii/Solution.java deleted file mode 100644 index 519f910..0000000 --- a/_includes/_root/reverse-linked-list-ii/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseBetween(ListNode head, int m, int n) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(head == null) return null; - if(head.next == null) return head; - - int c = 1; - - final ListNode _head = head; - - ListNode prev = null; - - ListNode jointLeft = null; - ListNode jointRight = null; - - while(head != null){ - - ListNode t = head.next; - - if(c == m){ - jointLeft = prev; - jointRight = head; - } - - if(c >= m && c <= n){ - head.next = prev; - } - - prev = head; - head = t; - - if(c == n){ - if(jointLeft != null){ - jointLeft.next = prev; - } - jointRight.next = head; - - if(jointRight == _head){ - return prev; - }else{ - return _head; - } - } - - c++; - - } - - return _head; - } -} \ No newline at end of file diff --git a/_includes/_root/reverse-nodes-in-k-group/README.md b/_includes/_root/reverse-nodes-in-k-group/README.md deleted file mode 100644 index e563f3d..0000000 --- a/_includes/_root/reverse-nodes-in-k-group/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Recursion - - * take at most `k` nodes from the linked list into `temp` - * reverse the `temp` if its length is `k` - * join the reversed linked list and `reverseKGroup(k + 1 node)` diff --git a/_includes/_root/reverse-nodes-in-k-group/Solution.java b/_includes/_root/reverse-nodes-in-k-group/Solution.java deleted file mode 100644 index 739b608..0000000 --- a/_includes/_root/reverse-nodes-in-k-group/Solution.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode reverseKGroup(ListNode head, int k) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if(k <= 1) return head; - - if(head == null) return null; - if(head.next == null) return head; - - ListNode tail = head; - ListNode prev = null; - - for(int i = 0; i < k ; i++){ - if(head == null){ - - // rollback - head = prev; - prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - tail.next = reverseKGroup(head, k); - - return prev; - - } -} \ No newline at end of file diff --git a/_includes/_root/reverse-words-in-a-string/README.md b/_includes/_root/reverse-words-in-a-string/README.md deleted file mode 100644 index 7c2b58a..0000000 --- a/_includes/_root/reverse-words-in-a-string/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Split Reverse and Join - - 1. split by `' '` into array - 1. reverse the array - 1. join the reversed array using `' '` - - -Here is my python version - -``` -class Solution: - # @param s, a string - # @return a string - def reverseWords(self, s): - return ' '.join(s.split()[::-1]) - -``` - -just do it in java diff --git a/_includes/_root/reverse-words-in-a-string/Solution.java b/_includes/_root/reverse-words-in-a-string/Solution.java deleted file mode 100644 index b760659..0000000 --- a/_includes/_root/reverse-words-in-a-string/Solution.java +++ /dev/null @@ -1,35 +0,0 @@ -public class Solution { - public String reverseWords(String s) { - if(s == null) return null; - - - ArrayList words = new ArrayList(); - - StringBuilder buff = new StringBuilder(); - - for(char c : (s + " ").toCharArray()){ - if (c != ' '){ - buff.append(c); - }else{ - String w = buff.toString(); - if(!"".equals(w)){ - words.add(w); - buff = new StringBuilder(); - } - } - } - - if(words.size() == 0) return ""; - - buff = new StringBuilder(); - for(int i = words.size() - 1; i >0 ; i--){ - buff.append(words.get(i)); - buff.append(' '); - } - - buff.append(words.get(0)); - - return buff.toString(); - - } -} \ No newline at end of file diff --git a/_includes/_root/roman-to-integer/README.md b/_includes/_root/roman-to-integer/README.md deleted file mode 100644 index 4aea8f5..0000000 --- a/_includes/_root/roman-to-integer/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## [Roman numerals](http://en.wikipedia.org/wiki/Roman_numerals) - -Loop invariant. Numerals should be in non-ascending order. The value is the sum of the numerals. -if some of numerals break the order, rollback their values added to the sum. - -e.g. - -``` -s = 'IIV' - -sum = 0 -for i in s - if s[i - 1] < s[i] - j = i - until s[j - 1] > s[j] - sum = sum - s[j]'s value * 2 // rollback - else - sum = sum + s[i]'s value - -``` diff --git a/_includes/_root/roman-to-integer/Solution.java b/_includes/_root/roman-to-integer/Solution.java deleted file mode 100644 index de87539..0000000 --- a/_includes/_root/roman-to-integer/Solution.java +++ /dev/null @@ -1,55 +0,0 @@ -public class Solution { - - /* - http://en.wikipedia.org/wiki/Roman_numerals - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1,000 - - to avoid four characters being repeated in succession - */ - - static final int[] N = { 1 , 5, 10, 50, 100, 500, 1000 }; - static final char[] C = {'I', 'V', 'X', 'L', 'C' , 'D', 'M' }; - - int index(char c){ - for(int i = 0 ; i < C.length; i++){ - if (C[i] == c) - return i; - } - - return -1; - } - - int rtoi(char c){ - return N[index(c)]; - } - - public int romanToInt(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(s.length() <= 0) return 0; - - char[] cs = s.toCharArray(); - - int sum = rtoi(cs[0]); - - for (int i = 1 ; i < cs.length; i++){ - sum += rtoi(cs[i]); - - int j = i - 1; - int ci = index(cs[i]); - - while(j>=0 && index(cs[j]) < ci){ - sum -= rtoi(cs[j--]) * 2; - } - } - - - return sum; - } -} \ No newline at end of file diff --git a/_includes/_root/rotate-image/README.md b/_includes/_root/rotate-image/README.md deleted file mode 100644 index b33c9f5..0000000 --- a/_includes/_root/rotate-image/README.md +++ /dev/null @@ -1,62 +0,0 @@ -## [Transpose](http://en.wikipedia.org/wiki/Transpose) then Reverse - -You must know this method, or it is difficult. - -``` -+---+---+ -| 1 | 2 | -+---+---+ -| 3 | 4 | -+---+---+ -``` - -Transpose: reflect the matrix over the main diagonal. - - -``` -Before - -+ - +---+---+ - | + | 2 | - +---+---+ - | 3 | + | - +---+---+ - + - -After - -+ - +---+---+ - | 1 | 3 | - +---+---+ - | 2 | 4 | - +---+---+ - + -``` - -Reverse: exchange each number along the vertical line in the middle - -``` -Before - - | -+---+---+ -| 1 | 3 | -+---+---+ -| 2 | 4 | -+---+---+ - | - - -After - - | -+---+---+ -| 3 | 1 | -+---+---+ -| 4 | 2 | -+---+---+ - | - -``` diff --git a/_includes/_root/rotate-image/Solution.java b/_includes/_root/rotate-image/Solution.java deleted file mode 100644 index f35fecd..0000000 --- a/_includes/_root/rotate-image/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -public class Solution { - public void rotate(int[][] matrix) { - - - final int mx = matrix.length; - final int my = matrix[0].length; - int x,y; - - int t; - - int _my = my - 1; - for(x = 0; x < mx - 1; x++){ - for(y = 0; y < _my; y++){ - int ny = mx - 1 - x; - int nx = my - 1 - y; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - - } - _my--; - } - - - for(x = 0; x < mx ; x++){ - for(y = 0 ; y < my / 2; y++){ - int ny = my - 1 - y; - int nx = x; - - t = matrix[y][x]; - matrix[y][x] = matrix[ny][nx]; - matrix[ny][nx] = t; - } - } - - } -} \ No newline at end of file diff --git a/_includes/_root/rotate-list/README.md b/_includes/_root/rotate-list/README.md deleted file mode 100644 index 48cd219..0000000 --- a/_includes/_root/rotate-list/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Cut and join - - * find the length of the linked list `len` - * make sure `n < len`, `n = n % len` - * cut at `len - n - 1` - * join the tail and head of the linked list diff --git a/_includes/_root/rotate-list/Solution.java b/_includes/_root/rotate-list/Solution.java deleted file mode 100644 index efb2005..0000000 --- a/_includes/_root/rotate-list/Solution.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode rotateRight(ListNode head, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(head == null) return null; - - ListNode _head = head; - - ListNode node = head; - int len = 1; - while(node.next != null){ - len++; - node = node.next; - } - - n %= len; - - ListNode tail = node; - - node = head; - for(int i = 0; i < len - n - 1; i++) node = node.next; - - tail.next = head; - ListNode rt = node.next; - node.next = null; - - return rt; - - } -} \ No newline at end of file diff --git a/_includes/_root/same-tree/README.md b/_includes/_root/same-tree/README.md deleted file mode 100644 index 9a3f501..0000000 --- a/_includes/_root/same-tree/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Definition - -``` -isSameTree(p, q) = - Same Val - Same Left Tree - Same Right Tree - -``` diff --git a/_includes/_root/same-tree/Solution.java b/_includes/_root/same-tree/Solution.java deleted file mode 100644 index a5806c2..0000000 --- a/_includes/_root/same-tree/Solution.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - - if(p == null && q == null){ - return true; - }else if(p == null || q == null){ - return false; - } - - return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } -} \ No newline at end of file diff --git a/_includes/_root/scramble-string/README.md b/_includes/_root/scramble-string/README.md deleted file mode 100644 index 8a42161..0000000 --- a/_includes/_root/scramble-string/README.md +++ /dev/null @@ -1,127 +0,0 @@ -## Guessing - -First time I meet this problem, an idea come to my mind is that - -``` -s1 = s1_left + s1_right -s2 = s2_left + s2_right - -isScramble(s1, s2) = isScramble(s1_left, s2_left) && isScramble(s1_right, s2_right) - || isScramble(s1_left, s2_right) && isScramble(s1_right, s2_left) - -isScramble(s1, s2) = s1 == s2 if s1.length == s2.length == 1 -``` - -brute force every left and right of s, will find the anwser. - -``` -foreach cutpoint in s1 - cut s1 into s1_left + s1_right - cut s2 into s2_left + s2_right - - if isScramble(....) - return True - -return False -``` - - -## Time Limited Optimizing - -Brute force code can't pass testcases on leetcode. -I try to use the method like `fib(n)` to generate all the `Scramble String`, I just want to make a cache at first. - -``` -let s = '0123' - -scramble(s) = [scramble(0) * scramble(123)] + [scramble(123) * scramble(0)] - +[scramble(01) * scramble(23)] + [scramble(23) * scramble(01)] - +[scramble(012) * scramble(3)] + [scramble(3) * scramble(012)] - -scramble return a two_part_set and * here means cartesian product -``` - -after write down things above, -I found only half of the results `scramble string` could have its first letter to be `0` - -e.g. -``` -[scramble(0) * scramble(123)] + [scramble(01) * scramble(23)] + [scramble(012) * scramble(3)] -``` -will yield a `scramble string` in form of `0XXX` - -that means we can make a filter to remove all `set` must not take `0` as its first letter -and `1` as it second and so on... - -so we build a methd -``` -check_has_char(pos, letter, two_part_set) - set = pos -> left_set or right_set depends on the two_part_set pivot - - return set contains letter -``` - -isScramble should be like - -``` -all_result_list = scramble(s1) - -foreach letter and pos in s2 - foreach result in all_result_list - if not check_has_char(pos, letter, result) - remove result from all_result_list - - if all_result_list is empty - return False - -``` - -`scramble(s1)` here compute only one level, which means -`all_result_list` contains objects like `[0|123] [01|23] ...` - -### What to do with survival objects in `all_result_list` - -A survial object, lets say `[0|123]`, what we need to do is that -check `isScramble(s1_left, s2_left) && isScramble(s1_right, s2_right)` - -here -``` -s1_left (gerated `set[0]`) -s1_right (gerated `set[123]`) -``` - -if checking passed, then isScramble(s1, s2) = True - -## Deal with duplicated elements - -above method will fail if there are duplicated elements. because we use a set to store left and right part of string. - -``` -scramble(1122) = [1|12] + [12|1] - +[1|2] + [1|2] - +[12|2] + [2|12] -``` - -to make that case work, chage the `set` to `set_with_count` - - -``` -scramble(1122) = [1(2)|1(1)2(1)] + [1(1)2(1)|1(2)] - +[1(2)|2(2)] + [1(2)|2(2)] - +[1(2)2(1)|2(1)] + [2(1)|1(2)2(1)] -``` - -we have to make some change to `check_has_char` - -``` -check_has_char(pos, letter, need_count, two_part_set) - pos -> left_set or right_set depends on the two_part_set pivot - - if pos on the left_set - return left_set contains letter count >= need_count - - if pos on the right_set - return left_set contains letter count + right_set contains letter count >= need_count -``` - - diff --git a/_includes/_root/scramble-string/Solution.java b/_includes/_root/scramble-string/Solution.java deleted file mode 100644 index 7323b3c..0000000 --- a/_includes/_root/scramble-string/Solution.java +++ /dev/null @@ -1,173 +0,0 @@ -public class Solution { - - static class Board { - - HashMap left = new HashMap(); - HashMap right = new HashMap(); - - String leftString; - String rightString; - - HashMap part(int idx){ - if(idx < left.size()){ - return left; - } else { - return right; - } - - } - - void add(Map m, Character c){ - Integer cnt = m.get(c); - - if(cnt == null){ - m.put(c, 1); - return; - } - - m.put(c, cnt + 1); - - } - - void addLeft(Character c){ - add(left, c); - } - - void addRight(Character c){ - add(right, c); - } - - int count(Map m, Character c){ - Integer cnt = m.get(c); - if(cnt == null) return 0; - - return cnt; - } - - boolean hasChar(int idx, Character c, int count){ - - HashMap m = part(idx); - - if(m == left){ - return count(m, c) >= count; - } - - return count(left, c) + count(right, c) >= count; - } - } - - List buildTwo(char[] all, int p){ - - Board b = new Board(); - - StringBuilder leftString = new StringBuilder(); - StringBuilder rightString = new StringBuilder(); - - for(int i = 0; i < all.length; i++){ - - Character c = all[i]; - if(i < p){ - leftString.append(c); - b.addLeft(c); - }else{ - rightString.append(c); - b.addRight(c); - } - } - - b.leftString = leftString.toString(); - b.rightString = rightString.toString(); - - Board mb = new Board(); - mb.left = new HashMap(b.right); - mb.right = new HashMap(b.left); - - mb.leftString = b.rightString; - mb.rightString = b.leftString; - - return Arrays.asList(new Board[]{b, mb}); - } - - boolean checkSameChar(char[] s1, char[] s2){ - s1 = Arrays.copyOf(s1, s1.length); - s2 = Arrays.copyOf(s2, s2.length); - - Arrays.sort(s1); - Arrays.sort(s2); - return Arrays.equals(s1, s2); - } - - static final Board SEP = new Board(); - - public boolean isScramble(String s1, String s2) { - - char[] _s1 = s1.toCharArray(); - char[] _s2 = s2.toCharArray(); - - if(_s1.length != _s2.length) - return false; - - if(_s1.length == 0) return true; - if(_s1.length == 1) return _s1[0] == _s2[0]; - if(!checkSameChar(_s1, _s2)) - return false; - - - LinkedList exp = new LinkedList(); - - for(int i = 1; i < _s1.length; i++){ - exp.addAll(buildTwo(_s1, i)); - } - - exp.add(SEP); - - HashMap counting = new HashMap(); - - for(int i = 0; i < _s2.length; i++){ - - Character c = _s2[i]; - - Integer cnt = counting.get(c); - - if(cnt == null){ - cnt = 0; - counting.put(c, 1); - }else{ - counting.put(c, cnt + 1); - } - - while(true){ - Board b = exp.poll(); - - if(b == SEP){ - if(exp.isEmpty()) - return false; - - exp.add(SEP); - break; - } - - if(b.hasChar(i, c, cnt + 1)){ - exp.add(b); - } - - } - - } - - for(Board b : exp){ - if(b != SEP){ - - if(isScramble(b.leftString , s2.substring(0, b.leftString.length()) ) - && isScramble(b.rightString, s2.substring(b.leftString.length()))) { - return true; - } - - } - } - - return false; - - } - -} \ No newline at end of file diff --git a/_includes/_root/search-a-2d-matrix/README.md b/_includes/_root/search-a-2d-matrix/README.md deleted file mode 100644 index 4c3cca3..0000000 --- a/_includes/_root/search-a-2d-matrix/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## Variant of Binary Search - -We can convert this problem to binary search by convert the `2D index` to `1D index`. - -### 2D to 1D - -a `m * n` matrix has `m * n` values. so, it is a `0 .. (m * n - 1)` array. - - -a `10 * 8` matrix - -``` -(y) - 0 1 2 3 4 5 6 7 8 9 -000 001 002 003 004 005 006 007 008 009 0 (x) -010 011 012 013 014 015 016 017 018 019 1 -020 021 022 023 024 025 026 027 028 029 2 -030 031 032 033 034 035 036 037 038 039 3 -040 041 042 043 044 045 046 047 048 049 4 -050 051 052 053 054 055 056 057 058 059 5 -060 061 062 063 064 065 066 067 068 069 6 -070 071 072 073 074 075 076 077 078 079 7 -``` - -Note: - - * x here is from top to bottom, y is from left to right - * this is for making code to be `matrix[x][y]` - -`056` is at `matrix[5][6]` - - * `5 (x) = 56 / 10 (width)` - * `6 (y) = 56 % 10 (width)` - - -so convert index `i` to `x`, `y`: - - * `x = i / width` - * `y = i % width` diff --git a/_includes/_root/search-a-2d-matrix/Solution.java b/_includes/_root/search-a-2d-matrix/Solution.java deleted file mode 100644 index f40c863..0000000 --- a/_includes/_root/search-a-2d-matrix/Solution.java +++ /dev/null @@ -1,30 +0,0 @@ -public class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = matrix.length; - int my = matrix[0].length; - - final int count = mx * my; - - int l = 0, r = count; - - while(l < r){ - int m = (r + l) / 2; - - int x = m / my; - int y = m % my; - - if(matrix[x][y] == target) - return true; - else if(matrix[x][y] < target) - l = m + 1; - else - r = m; - - - } - - return false; - } -} \ No newline at end of file diff --git a/_includes/_root/search-for-a-range/README.md b/_includes/_root/search-for-a-range/README.md deleted file mode 100644 index 80096c5..0000000 --- a/_includes/_root/search-for-a-range/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Improved binary search - -There is no guarantee which one will be found when using a binary search and the input array has many same elements. - -What we need to do is after we got the index, search the left and right to expand the range. - - -``` - -if found - - left = index - right = index - - expand left while A[left] == target - expand right while A[right] == target - - -``` diff --git a/_includes/_root/search-for-a-range/Solution.java b/_includes/_root/search-for-a-range/Solution.java deleted file mode 100644 index 01bd046..0000000 --- a/_includes/_root/search-for-a-range/Solution.java +++ /dev/null @@ -1,29 +0,0 @@ -public class Solution { - public int[] searchRange(int[] A, int target) { - - int s = 0, e = A.length; - - while( s < e ){ - int mid = (s + e) / 2; - - if(A[mid] == target){ - - int _s = mid, _e = mid; - - while(_s - 1 >= 0 && A[_s - 1] == target) _s--; - while(_e + 1 < A.length && A[_e + 1] == target) _e++; - - return new int[]{_s, _e}; - - }else if(A[mid] < target){ - s = mid + 1; - }else if(A[mid] > target){ - e = mid; - } - - } - - return new int[]{-1, -1}; - - } -} \ No newline at end of file diff --git a/_includes/_root/search-in-rotated-sorted-array-ii/README.md b/_includes/_root/search-in-rotated-sorted-array-ii/README.md deleted file mode 100644 index ccea75d..0000000 --- a/_includes/_root/search-in-rotated-sorted-array-ii/README.md +++ /dev/null @@ -1,73 +0,0 @@ -## By [accident](http://en.wikipedia.org/wiki/Programming_by_permutation) Again - -using programming by accient we solved [Search in Rotated Sorted Array](../search-in-rotated-sorted-array). - -But, this time, We can t sure the target number is on the left or on the right of the `mid`. - -e.g. - -``` -t = 2 - -[ 1 1 1 1 1 1 2 1 1 1 1] - s m e -``` - -this time, we do not know `s = m + 1` or `e = m`. - -### Brute force again - -`s` `m` `e` may be like below. (put == or != between `s` `m` `e`) - - * `s` != `m` != `e` - * `s` != `m` == `e` - * `s` == `m` != `e` - * `s` == `m` == `e` - - -`s` != `m` != `e` - -this is handled by [Search in Rotated Sorted Array](../search-in-rotated-sorted-array). - - -`s` != `m` == `e` - -``` -[ 1 1 1 1 2 2 2 2 2 2 2] - s m e -``` - -`m` == `e` means `m` .. `e` are the same number. they are safe to be removed. -Remember, number at `m` does not equal to `t`, because we had checked `if A[m] == t` before. - - -`s` == `m` != `e` - -``` -[ 1 1 1 1 1 1 1 2 2 2 2] - s m e -``` - -this case is the same as `s` != `m` == `e` - - -`s` == `m` == `e` - -Wrost case - -``` -t = 2 - -[ 1 1 1 1 1 1 2 1 1 1 1] - s m e -``` - -we only know `t` does not equal to `s` `m` or `e`. - -what we can do it only search again by doing - -``` -s = s + 1 -e = e - 1 -``` - diff --git a/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java b/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java deleted file mode 100644 index fea9221..0000000 --- a/_includes/_root/search-in-rotated-sorted-array-ii/Solution.java +++ /dev/null @@ -1,60 +0,0 @@ -public class Solution { - public boolean search(int[] A, int target) { - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return true; - } - - if(target < A[mid]){ - // normal in first half - if (A[s] == A[mid]) { - if(A[mid] == A[e - 1]){ - // special - - s++; - e--; - - }else{ - s = mid + 1; - } - - } else if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - if (A[mid] == A[e - 1]) { - if(A[s] == A[mid]){ - s++; - e--; - }else{ - e = mid; - } - - - } else if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return false; - } -} \ No newline at end of file diff --git a/_includes/_root/search-in-rotated-sorted-array/README.md b/_includes/_root/search-in-rotated-sorted-array/README.md deleted file mode 100644 index e42127e..0000000 --- a/_includes/_root/search-in-rotated-sorted-array/README.md +++ /dev/null @@ -1,139 +0,0 @@ -## Normal binary seach - -just reciting a binary search code - -``` - -while s < e - - mid = (s + e) / 2 - - if target == A[mid] - return mid - else if target < A[mid] - e = mid - else if target > A[mid] - s = mid + 1 - - -``` - -## Binary search essential - -Each time we separate the numbers into two parts. -After the target number compared to the mid number, we are sure which part that the target number must be in. - - -## Which part the target must be - -In this case, there is no duplicate, so the target must be either in left part or right part. - -What we need to do is to determine which part. - -``` - -while s < e - - mid = (s + e) / 2 - - if target == A[mid] - return mid - else if on the left - e = mid - else if on the right - s = mid + 1 - - -``` - -### Brute force - -Dont be brainfucked. so just write down all possible `s`,`m`,`e` and `t`. - -`t` is either on the left side or right side of `m`. - -``` -[s t m e] - -or - -[s m t e] -``` - -and `s` `m` `e` may be like below. (put `<` or `>` between `s` `m` `e`) - - * `s` < `m` < `e` - * `s` < `m` > `e` - * `s` > `m` < `e` - * `s` > `m` > `e` - - -`s` < `m` < `e` (normal binary search) - - -``` - 1 E - 2 * - 3 * - 4 * - 5 * - 6 M - 7 * - 8 * - 9 * - 10 S -``` - -`s` < `m` > `e` - - -``` - 1 * - 2 * - 3 M - 4 * - 5 * - 6 * - 7 S - 8 E - 9 * - 10 * -``` - -`s` > `m` < `e` - -``` - 1 * - 2 * - 3 S - 4 E - 5 * - 6 * - 7 * - 8 M - 9 * - 10 * -``` - -`s` > `m` > `e` - -this is not a sorted array - - -#### After got all the possible cases - -2 (`t` either on the left or on the right of `m` ) * 3 ( relations of `s` `m` `t` ) = 6 cases - -each case choose either the left part(`e = m`) or the right part(`s = m + 1`) of input array. - - -You can determine which part to choose by your brain or by [accident](http://en.wikipedia.org/wiki/Programming_by_permutation). - -Dont worry, if you choose part by accident, it is at most 64 tries. - - - - - - - diff --git a/_includes/_root/search-in-rotated-sorted-array/Solution.java b/_includes/_root/search-in-rotated-sorted-array/Solution.java deleted file mode 100644 index b185f3c..0000000 --- a/_includes/_root/search-in-rotated-sorted-array/Solution.java +++ /dev/null @@ -1,43 +0,0 @@ -public class Solution { - public int search(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int s = 0; - int e = A.length; - - while(s < e){ - int mid = (s + e) /2; - - if(A[mid] == target){ - return mid; - } - - if(target < A[mid]){ - // normal in first half - - if(A[s] <= A[mid] && A[s] <= target){ - e = mid; - // abnormal - }else if(A[mid] <= A[e - 1]){ - e = mid; - }else { - s = mid + 1; - } - - } else { - - // normal in last half - - if(A[mid] <= A[e - 1] && target <= A[e - 1]){ - s = mid + 1; - } else if(A[s] <= A[mid]) { - s = mid + 1; - } else { - e = mid; - } - - } - } - - return -1; - } -} \ No newline at end of file diff --git a/_includes/_root/search-insert-position/README.md b/_includes/_root/search-insert-position/README.md deleted file mode 100644 index dcbafcd..0000000 --- a/_includes/_root/search-insert-position/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## The core tech of InsertionSort - -a InsertionSort is like - - -``` -sorted is an array to store sorted values - -foreach value in input - - p = search_insert_position(sorted_array, value) - - insert value at p in the sorted_array - -``` - - -## Where to insert - -The sorted array is in non-descending order. The first A[i] greater than or equals to the `value` is where to insert the `value`. diff --git a/_includes/_root/search-insert-position/Solution.java b/_includes/_root/search-insert-position/Solution.java deleted file mode 100644 index a47f99b..0000000 --- a/_includes/_root/search-insert-position/Solution.java +++ /dev/null @@ -1,9 +0,0 @@ -public class Solution { - public int searchInsert(int[] A, int target) { - // Note: The Solution object is instantiated only once and is reused by each test case. - for(int i = 0; i < A.length; i++){ - if(A[i] >= target) return i; - } - return A.length; - } -} \ No newline at end of file diff --git a/_includes/_root/set-matrix-zeroes/README.md b/_includes/_root/set-matrix-zeroes/README.md deleted file mode 100644 index c31a687..0000000 --- a/_includes/_root/set-matrix-zeroes/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## O(m + n) - -A matrix has m rows and n columns. - -It is easy to collect all information into `to_zero_row[m]` and `to_zero_col[n]`. - -## O(1) - -If you can write a O(m + n) code, then you can write O(1). - -The idea is tricky, Just treat the first row and first column as `to_zero_row[m]` and `to_zero_col[n]`. - -And, you need `2` variables to store if the first row and the first colum were needed to be zeroed. diff --git a/_includes/_root/set-matrix-zeroes/Solution.java b/_includes/_root/set-matrix-zeroes/Solution.java deleted file mode 100644 index 09d5995..0000000 --- a/_includes/_root/set-matrix-zeroes/Solution.java +++ /dev/null @@ -1,65 +0,0 @@ -public class Solution { - public void setZeroes(int[][] matrix) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(matrix == null) return; - int mx = matrix.length; - if ( mx == 0) return; - int my = matrix[0].length; - - int x, y; - - boolean xfz = false, yfz = false; - - for(x = 0; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - xfz = true; - break; - } - } - - for(y = 0; y < my ; y++ ){ - if(matrix[0][y] == 0){ - yfz = true; - break; - } - } - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my ; y++){ - if(matrix[x][y] == 0){ - matrix[x][0] = 0; - matrix[0][y] = 0; - } - } - } - - for(x = 1; x < mx ; x++ ){ - if(matrix[x][0] == 0){ - for(y = 0; y < my; y++){ - matrix[x][y] = 0; - } - } - } - - for(y = 1; y < my ; y++ ){ - if(matrix[0][y] == 0){ - for(x = 0; x < mx; x++){ - matrix[x][y] = 0; - } - } - } - - if(xfz){ - for(x = 0; x < mx ; x++ ){ - matrix[x][0] = 0; - } - } - - if(yfz){ - for(y = 0; y < my ; y++ ){ - matrix[0][y] = 0; - } - } - } -} \ No newline at end of file diff --git a/_includes/_root/simplify-path/README.md b/_includes/_root/simplify-path/README.md deleted file mode 100644 index fd638b9..0000000 --- a/_includes/_root/simplify-path/README.md +++ /dev/null @@ -1,48 +0,0 @@ -## eat++ - -I like eating. - - * `.` eats itself - * `..` eats not only itself but also the directory on the its left - -So what we need to is - - 1. split path string by `/` - 1. copy each directory's name if it is not eaten by someting - 1. join the copied result - -how to split and join are easy, and can be find in [Reverse Words in a String](../reverse-words-in-a-string) - - -### eat while copying - -`eat` is a number indicates how many directories are eaten. - -``` -eat = 0 - -foreach dirname in reverse order - if dirname is '.' - // eat itself - // just dont copy to target - if dirname is '..' - // eat itself and the left - // dont copy - - // indicate to eat the left one - eat = eat + 1 - else - // real directory - if eat > 0 - // this one is eaten - // dont copy - - // eaten - eat = eat - 1 - else - - copy directory's name to target collection - - -``` - diff --git a/_includes/_root/simplify-path/Solution.java b/_includes/_root/simplify-path/Solution.java deleted file mode 100644 index fb04589..0000000 --- a/_includes/_root/simplify-path/Solution.java +++ /dev/null @@ -1,44 +0,0 @@ -public class Solution { - public String simplifyPath(String path) { - - String[] names = path.split("/"); - - int eat = 0; - - LinkedList stack = new LinkedList(); - - for(int i = names.length - 1; i >= 0; i--){ - - String token = names[i]; - - if("..".equals(token)){ - eat++; - }else if(".".equals(token)){ - // do nothing - }else if("".equals(token)){ - // do nothing - }else { - - // dir name - if(eat > 0){ - eat--; - }else{ - stack.push(token); - } - } - } - - StringBuilder s = new StringBuilder(); - - s.append("/"); - - while(stack.size() > 1){ - s.append(stack.pop()); - s.append("/"); - } - - if(!stack.isEmpty()) s.append(stack.pop()); - - return s.toString(); - } -} diff --git a/_includes/_root/single-number-ii/README.md b/_includes/_root/single-number-ii/README.md deleted file mode 100644 index cda93f1..0000000 --- a/_includes/_root/single-number-ii/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Improved version of [Single Number](../single-number) - -`xor` can not work if the number appears 3 times. - -### Yet another tricky bit manipulation - -[1,2,3,5,1,2,3,1,2,3] in binary form of - -``` -0 0 0 1 -0 0 1 0 -0 0 1 1 -0 1 1 0 -0 0 0 1 -0 0 1 0 -0 0 1 1 -0 0 0 1 -0 0 1 0 -0 0 1 1 - -count 0 and 1 - -0 1 7 6 -``` -then remove the number which `mod 3 == 0` in 0 1 7 6 to 0. the number becomes 0 1 1 0 in decimal form (5). - -use an array to count how many `1` appears, the final bit depends on the count number. diff --git a/_includes/_root/single-number-ii/Solution.java b/_includes/_root/single-number-ii/Solution.java deleted file mode 100644 index eae2915..0000000 --- a/_includes/_root/single-number-ii/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[] count = new int[Integer.SIZE]; - int[] bit = new int[Integer.SIZE]; - - Arrays.fill(count, 0); - Arrays.fill(bit, 0); - - for(int a : A){ - - for(int b = 0; b < Integer.SIZE; b++){ - int x = a >>> b & 1; - bit[b] |= x; - - if(x == 1) - count[b]++; - } - - } - - int s = 0; - for(int b = 0; b < Integer.SIZE; b++ ){ - if (count[b] % 3 != 0) - s |= bit[b] << b; - } - - return s; - - } -} \ No newline at end of file diff --git a/_includes/_root/single-number/README.md b/_includes/_root/single-number/README.md deleted file mode 100644 index d1793b2..0000000 --- a/_includes/_root/single-number/README.md +++ /dev/null @@ -1,28 +0,0 @@ -## Tricky bit manipulation - -I have no idea at first, and search for the answer. The solution is using a tricky bit manipulation of `XOR`. - -`XOR` will set same bit to `0`, otherwise `1`. so if a number appear even number times, `XOR` will erase it. - -e.g. - -`[1,2,3,4,1,2,3]` in binary form of - - -``` -0 0 0 1 -0 0 1 0 -0 0 1 1 -0 1 0 0 -0 0 0 1 -0 0 1 0 -0 0 1 1 - -count 0 and 1 - -0 1 4 4 - -``` - -then remove the even number in `0 1 4 4` to `0`. the number becomes `0 1 0 0` in decimal form (4). - diff --git a/_includes/_root/single-number/Solution.java b/_includes/_root/single-number/Solution.java deleted file mode 100644 index 5d80c1c..0000000 --- a/_includes/_root/single-number/Solution.java +++ /dev/null @@ -1,13 +0,0 @@ -public class Solution { - public int singleNumber(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if (A.length == 1) return A[0]; - int s = A[0]; - - for(int i = 1; i< A.length; i++) - s ^= A[i]; - - return s; - - } -} \ No newline at end of file diff --git a/_includes/_root/sort-colors/README.md b/_includes/_root/sort-colors/README.md deleted file mode 100644 index 9a90fbe..0000000 --- a/_includes/_root/sort-colors/README.md +++ /dev/null @@ -1,101 +0,0 @@ -## A sad tale - -Arrays.sort would be O(nlgn). - - -## Loop invariant - -### Two colors (Red White) - -Like insertion sort, there is a wall. Colors on the left side of the wall are sorted, on the right side are unsorted. - -In this case, there is also a good news. No need to find the inserting position. -The sorting process is like that taking all the `red` color out from the colors, and the rest of colors must be `white`. -So just combine `red` and `white`. - - -#### Use no extra space to put the `red` colors. - -In another word, do the sort in place. - -let an variable to store the `wall`'s pointer, offset less than the `wall` should be `red` in the input array. When a new `red` color comes, increase the `wall`'s pointer and swap what the `wall` points to (`must be white`) and the new `red` color. - -``` -[ r w r w r w ] - - ^ ^ - W p - - -red found on p - -swap - -[ r w r w r w ] - - ^ ^ - W p - - -increase wall pointer - -[ r w r w r w ] - - ^ ^ - W p - -red found on p - -swap - -[ r r w w r w ] - - ^ ^ - W p - - -loop ... -``` - -### Three Colors - -When `blue` was added, just add a new `wall` for reserving `blue` at the end of the input array. - - -``` -blue found on p - -[ r r w b w b r w b] - - ^ ^ ^ - W p B - - -swap - -[ r r w b w b r w b] - - ^ ^ ^ - W p B - - -increase B's wall - -[ r r w b w b r w b] - - ^ ^ ^ - W p B - -swap - -[ r r w w w b r b b] - - ^ ^ ^ - W p B - -loop... -``` - - - - diff --git a/_includes/_root/sort-colors/Solution.java b/_includes/_root/sort-colors/Solution.java deleted file mode 100644 index 3749c0e..0000000 --- a/_includes/_root/sort-colors/Solution.java +++ /dev/null @@ -1,36 +0,0 @@ -public class Solution { - public void sortColors(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int red = 0; - int blue = A.length - 1; - - int p = 0; - - int t = 0; - - while(p <= blue){ - - if(A[p] == 0){ //red - t = A[p]; - A[p] = A[red]; - A[red] = t; - - red++; - p++; - - }else if(A[p] == 2){ // blue - t = A[p]; - A[p] = A[blue]; - A[blue] = t; - - blue--; - }else{ // white - - p++; - - } - - } - } -} \ No newline at end of file diff --git a/_includes/_root/sort-list/README.md b/_includes/_root/sort-list/README.md deleted file mode 100644 index e557173..0000000 --- a/_includes/_root/sort-list/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## MergeSort - - * cut in the middle - * MergeSort(left) and MegerSort(right) - * merge using [Merge Two Sorted Lists](../merge-two-sorted-lists) - - -### Finding the middle of a linked list - -fast-slow pointer. - - 1. fast runner goes 2 steps each time - 1. slow runner goes 1 step - 1. when fast reach the end of the linked list, the slow id the middle of the list diff --git a/_includes/_root/sort-list/Solution.java b/_includes/_root/sort-list/Solution.java deleted file mode 100644 index 7407309..0000000 --- a/_includes/_root/sort-list/Solution.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - // Note: The Solution object is instantiated only once and is reused by each test case. - ListNode rt = new ListNode(0); - ListNode h = rt; - - while( l1 != null && l2 != null){ - if(l1.val < l2.val){ - rt.next = l1; - l1 = l1.next; - }else{ - rt.next = l2; - l2 = l2.next; - } - - rt = rt.next; - } - - if(l1 != null) rt.next = l1; - else rt.next = l2; - - - return h.next; - - - } - - - public ListNode sortList(ListNode head) { - if(head == null) return null; - if(head.next == null) return head; - - ListNode fast = head.next; - ListNode slow = head; - - while(fast != null && fast.next != null){ - slow = slow.next; - fast = fast.next.next; - } - - ListNode h2 = slow.next; - slow.next = null; - - return mergeTwoLists(sortList(head), sortList(h2)); - - - } -} \ No newline at end of file diff --git a/_includes/_root/spiral-matrix-ii/README.md b/_includes/_root/spiral-matrix-ii/README.md deleted file mode 100644 index 4e511f4..0000000 --- a/_includes/_root/spiral-matrix-ii/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Opposite to [Spiral Matrix I](../spiral-matrix) - -`Spiral Matrix I` is a reader, it reads numbers from the matrix. - -`Spiral Matrix II` is a writer, it writes numbers into the matrix. diff --git a/_includes/_root/spiral-matrix-ii/Solution.java b/_includes/_root/spiral-matrix-ii/Solution.java deleted file mode 100644 index 0a30f2c..0000000 --- a/_includes/_root/spiral-matrix-ii/Solution.java +++ /dev/null @@ -1,43 +0,0 @@ -public class Solution { - public int[][] generateMatrix(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int[][] rt = new int[n][n]; - if(n <= 0) return rt; - - int c = 1; - - int x = 0, y = 0, my = n , mx = n; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my; i++){ - rt[y][i] = c++; - } - - y++; - - for(int i = y; i < my && x < mx ; i++ ){ - rt[i][mx - 1] = c++; - } - - mx--; - - for(int i = mx - 1; i >= x && y < my; i--){ - rt[my - 1][i] = c++; - } - - my--; - - for(int i = my - 1; i>= y && x < mx; i--){ - rt[i][x] = c++; - } - - x++; - - } - - return rt; - - - } -} \ No newline at end of file diff --git a/_includes/_root/spiral-matrix/README.md b/_includes/_root/spiral-matrix/README.md deleted file mode 100644 index e74352a..0000000 --- a/_includes/_root/spiral-matrix/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Simulating - -Walk to the matrix's boarder and then change the direction in the order of `left`, `down`, `right` and `up`. diff --git a/_includes/_root/spiral-matrix/Solution.java b/_includes/_root/spiral-matrix/Solution.java deleted file mode 100644 index e4dc0ba..0000000 --- a/_includes/_root/spiral-matrix/Solution.java +++ /dev/null @@ -1,41 +0,0 @@ -public class Solution { - public List spiralOrder(int[][] matrix) { - ArrayList rt = new ArrayList(); - - if(matrix.length == 0) return rt; - - int x = 0, y = 0, my = matrix.length, mx = matrix[0].length; - //int dx = 1, dy = 1; - - while(x < mx && y < my){ - for(int i = x; i < mx && y < my ; i++){ - rt.add(matrix[y][i]); - } - - y++; - - for(int i = y; i< my && x < mx; i++){ - rt.add(matrix[i][mx - 1]); - } - - mx--; - - for(int i = mx - 1; i >= x && y < my ; i--){ - rt.add(matrix[my - 1][i]); - } - - my--; - - for(int i = my - 1; i >= y && x < mx; i--){ - rt.add(matrix[i][x]); - } - - x++; - - } - - - return rt; - - } -} diff --git a/_includes/_root/sqrtx/README.md b/_includes/_root/sqrtx/README.md deleted file mode 100644 index 3289b7a..0000000 --- a/_includes/_root/sqrtx/README.md +++ /dev/null @@ -1,69 +0,0 @@ -## [Newton's Method](http://en.wikipedia.org/wiki/Newton%27s_method) - -This is copied from my friend Newton. - -Then I wrote this code: - -``` -public int sqrt(int x) { - if(x < 0) return -1; - if(x == 0) return 0; - - // x/t + t = 2t - double t = (double)x; - double tt = 0; - while( (int)tt - (int)t != 0 ){ - tt = t; - t = (x/t + t) /2; - - } - - return (int)tt; -} -``` - -## Programming Way - -Well, I replaced the mathematical way finally, maybe, I think I should do this in programming way. - -### Brute Force - -Search through `1..x`, find the `i`, such that `i^2 == x` or `i^2 < x < (i + 1)^2`. - - -### Binary Search - -As we can brute force, and `1..x` is obviously ordered, we can do it by applying binary search pattern. - - -``` -treat 1..x as the content of an array[0..x-1] - - -while s < e - - m = (s + e) / 2 - - if (m + 1)^2 == x - return m + 1 - - if (m + 1)^2 < x < (m + 1 + 1)^2 - return m + 1 - - if x < (m + 1)^2 - e = m - else - s = m + 1 -``` - -#### Overflow - -The testcases contain some large numbers like `Integer.MAX_VALUE`, code will fail due to overflow. - -To avoid this, change any `+` and `*` to `-` and `/` - - * `m = (s + e) / 2` -> `m = (e - s) / 2 + s` - * `(m + 1)^2 == x` -> `x / (m + 1) == (m + 1)` - - - diff --git a/_includes/_root/sqrtx/Solution.java b/_includes/_root/sqrtx/Solution.java deleted file mode 100644 index 0fb77d9..0000000 --- a/_includes/_root/sqrtx/Solution.java +++ /dev/null @@ -1,41 +0,0 @@ -public class Solution { - public int sqrt(int x) { - - if(x < 0) return -1; - if(x == 0) return 0; - - int s = 0; - int e = x; - - - while(s < e){ - int m = (e - s) / 2 + s; - - int m1 = x / (m + 1); - int m2 = x / (m + 1 + 1); - - if(m + 1 == m1){ - return m + 1; - } - - if(m + 1 + 1 == m2){ - return m + 1 + 1; - } - - if(m + 1 < m1 && m2 < m + 1 + 1){ - return m + 1; - } - - - if(m1 < m + 1){ - e = m; - }else{ - s = m + 1; - } - - } - - - throw new RuntimeException(); - } -} diff --git a/_includes/_root/string-to-integer-atoi/README.md b/_includes/_root/string-to-integer-atoi/README.md deleted file mode 100644 index f5624c8..0000000 --- a/_includes/_root/string-to-integer-atoi/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Easy or Not Easy - -`atoi` is an easy problem, anyone can write some code to pass some of the testcase. - -`atoi` do have a low `AC Rates` at `14.5%` (Jul 27 2014). the problem testcases contains a lot of edge cases, which will make you depressed. - -Edges cases, including but not limited to the cases below: - - * Sign - * Whitespace - * Overflow diff --git a/_includes/_root/string-to-integer-atoi/Solution.java b/_includes/_root/string-to-integer-atoi/Solution.java deleted file mode 100644 index 53baea7..0000000 --- a/_includes/_root/string-to-integer-atoi/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -public class Solution { - public int atoi(String str) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - - // null "" - if (str == null || "".equals(str)) - return 0; - - char[] ds = str.toCharArray(); - - int sum = 0; - - int sign = 1; - - int s = 0; - - boolean signseen = false; - - while(s < ds.length && !('0' <= ds[s] && ds[s] <= '9')){ - - if(signseen) - return 0; - - - - if(ds[s] == '-'){ - sign *= -1; - signseen = true; - }else if(ds[s] == '+'){ - signseen = true; - }else if(ds[s] != ' '){ - return 0; - } - - s++; - } - - int e = s; - while(e < ds.length && ('0' <= ds[e] && ds[e] <= '9')){ - e++; - } - - int p = 0; - - boolean flago = false; - for(int i = s; i < e ; i++){ - - if(sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && ds[i] - '0' > Integer.MAX_VALUE % 10 )) - flago = true; - - sum = sum * 10 + (ds[i] - '0'); - } - - if (flago) - if(sign > 0) - return Integer.MAX_VALUE; - else - return Integer.MIN_VALUE; - - return sum * sign; - - } -} \ No newline at end of file diff --git a/_includes/_root/subsets-ii/README.md b/_includes/_root/subsets-ii/README.md deleted file mode 100644 index 73c5032..0000000 --- a/_includes/_root/subsets-ii/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## like [Subsets](../subsets) - -Subsets can provide all subset with dupicates, so before add a level to the result set, check if the level is already in the result set. diff --git a/_includes/_root/subsets-ii/Solution.java b/_includes/_root/subsets-ii/Solution.java deleted file mode 100644 index 676423c..0000000 --- a/_includes/_root/subsets-ii/Solution.java +++ /dev/null @@ -1,49 +0,0 @@ -public class Solution { - public List> subsetsWithDup(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if (num.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(num); - - long mask = (long) Math.pow(2, num.length); - - next: - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < num.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(num[(int)j]); - } - } - - next_lv: - for(List _level : rt){ - - if(_level.size() == level.size()){ - for(int li = 0; li < _level.size(); li++){ - if(!_level.get(li).equals(level.get(li))) - continue next_lv; - } - - continue next; - } - } - rt.add(level); - - } - - return rt; - - } -} diff --git a/_includes/_root/subsets/README.md b/_includes/_root/subsets/README.md deleted file mode 100644 index 8795a19..0000000 --- a/_includes/_root/subsets/README.md +++ /dev/null @@ -1,71 +0,0 @@ -## Each element is either in the subset or not - - * `*`: element is in subset - * `-`: element NOT in subset - -so subsets of `[1,2,3]` are - - -``` -[-,-,*] = [3] -[*,-,-] = [1] -[-,*,-] = [2] -[*,*,*] = [1,2,3] -[*,-,*] = [1,3] -[-,*,*] = [2,3] -[*,*,-] = [1,2] -[-,-,-] = [] - -``` - -some brute force codes may look like a DFS - - -``` - -search(pos) - - if found - output - - for state in IN, NOT_IN - if IN - subset[pos] = current element - else - subset[pos] = nothing - - search(pos + 1) - - -``` - -## Binary - -use binary to repsent only two states - - -``` -001 = [3] -100 = [1] -010 = [2] -111 = [1,2,3] -101 = [1,3] -011 = [2,3] -110 = [1,2] -000 = [] -``` - -binary => decimal (000 .. 111 => 0 .. 7) - - -``` -for i 0 .. 2^n - 1 - b = convert i to binary - - subset = select elements using b - - yield subset -``` - - - diff --git a/_includes/_root/subsets/Solution.java b/_includes/_root/subsets/Solution.java deleted file mode 100644 index f75027a..0000000 --- a/_includes/_root/subsets/Solution.java +++ /dev/null @@ -1,34 +0,0 @@ -public class Solution { - public List> subsets(int[] S) { - ArrayList> rt = new ArrayList>(); - - if (S.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - - Arrays.sort(S); - - long mask = (long) Math.pow(2, S.length); - - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < S.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(S[(int)j]); - } - } - - rt.add(level); - - } - - return rt; - } -} diff --git a/_includes/_root/substring-with-concatenation-of-all-words/README.md b/_includes/_root/substring-with-concatenation-of-all-words/README.md deleted file mode 100644 index 04db0d8..0000000 --- a/_includes/_root/substring-with-concatenation-of-all-words/README.md +++ /dev/null @@ -1,38 +0,0 @@ -## [Space-time tradeoff](http://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff) - -A brute force solution is easy. Yet, obviously, time limited. - -### Check concatenation using count sum - -cut a string `S` into N substring, lets say `s1 * 1, s2 * 2, s3 * 1`, -that is, `S` could be `s2s1s2s3` or `s3s1s2s2` or some string else. - -convert `L` to count sum, which is a map of `string to count` - -``` -M = empty Map - -for s in L - M[s] = M[s] + 1 - - -``` - - -check concatenation S by minus count - -``` -cut S into substrings by some length - -_M = clone of M - -for s in substrings - - if _M[s] == 0 - Not a concatenation - - _M[s] = _M[s] - 1 - - - -``` diff --git a/_includes/_root/substring-with-concatenation-of-all-words/Solution.java b/_includes/_root/substring-with-concatenation-of-all-words/Solution.java deleted file mode 100644 index cc4f943..0000000 --- a/_includes/_root/substring-with-concatenation-of-all-words/Solution.java +++ /dev/null @@ -1,61 +0,0 @@ -public class Solution { - - boolean checkCat(String s, HashMap lm, int wordLen){ - - while(s.length() > 0){ - String w = s.substring(0, wordLen); - - Integer v = lm.get(w); - - if(v == null) return false; - if(v == 0) return false; - - s = s.substring(wordLen); - - v--; - lm.put(w, v); - } - - - return true; - } - - public List findSubstring(String S, String[] L) { - - if(L.length == 0) return new ArrayList(); - - ArrayList rt = new ArrayList(); - - - HashMap lm = new HashMap(); - - for(String l : L){ - - Integer v = lm.get(l); - - if(v == null) v = 0; - v++; - - lm.put(l, v); - } - - - final int wordLen = L[0].length(); - - for(int i = 0; i + wordLen <= S.length(); i++){ - - if(lm.containsKey(S.substring(i, i + wordLen))){ - - if(i + wordLen * L.length > S.length()){ - break; - } - - if(checkCat(S.substring(i, i + wordLen * L.length), new HashMap(lm), wordLen)){ - rt.add(i); - } - } - } - - return rt; - } -} \ No newline at end of file diff --git a/_includes/_root/sudoku-solver/README.md b/_includes/_root/sudoku-solver/README.md deleted file mode 100644 index 86b2fb7..0000000 --- a/_includes/_root/sudoku-solver/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Just Combine [Valid Sudoku](../valid-sudoku) and [N-Queens](../n-queens) - -the only difference form [N-Queens](../n-queens) is the `possibility checker`. - -but, good news is that we have done [Valid Sudoku](../valid-sudoku). - - -## Time Limit - -The first version looks like [N-Queens](../n-queens) may exceed the time limit. - -### Fail fast. - -In this problem, if any grid is not solved, trying any further is needless. - -So, let `solveSudoku` return a flag to warn this way is blocked. diff --git a/_includes/_root/sudoku-solver/Solution.java b/_includes/_root/sudoku-solver/Solution.java deleted file mode 100644 index 62e3c4f..0000000 --- a/_includes/_root/sudoku-solver/Solution.java +++ /dev/null @@ -1,117 +0,0 @@ -public class Solution { - - static final List VALID = Arrays.asList(new Character[]{ '1' , '2', '3', '4', '5', '6', '7', '8', '9'}); - - boolean _solveSudoku(char[][] board){ - int mx = board.length; - int my = board[0].length; - - int x ,y; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - - if(board[x][y] == '.'){ - int _x, _y; - HashSet val = new HashSet(VALID); - - for(_y = 0; _y < my; _y++) - val.remove(board[x][_y]); - - for(_x = 0; _x < mx; _x++) - val.remove(board[_x][y]); - - int sx = x / 3 * 3; - int sy = y / 3 * 3; - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - val.remove(board[sx + ox][sy + oy]); - } - - for(char c : val){ - board[x][y] = c; - - if(isValidSudoku(board)){ - // try next '.' - if(_solveSudoku(board)){ - return true; - } - - // try another number - } - - board[x][y] = '.'; - } - - // board[x][y] is '.' return false to fail fast - return false; - } - - - } - } - - return true; - } - - public void solveSudoku(char[][] board) { - _solveSudoku(board); - } - - boolean isValidSudoku(char[][] board) { - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } - -} diff --git a/_includes/_root/sum-root-to-leaf-numbers/README.md b/_includes/_root/sum-root-to-leaf-numbers/README.md deleted file mode 100644 index 73ef4c9..0000000 --- a/_includes/_root/sum-root-to-leaf-numbers/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Definition - -``` -sumNumbers(node) = 0 [ empty tree ] - parent_val(node) + node.val [ node is leaf ] - sumNumbers(node.left) + sumNumbers(node.right) [ otherwise ] - -parent_val(node) = 0 [ node is root ] - parent_val(parent_node) + parent_node.val [ otherwise ] -``` - - -I have written some versions using DFS and BFS, but they are not as clear as above. diff --git a/_includes/_root/sum-root-to-leaf-numbers/Solution.java b/_includes/_root/sum-root-to-leaf-numbers/Solution.java deleted file mode 100644 index ce7fbfb..0000000 --- a/_includes/_root/sum-root-to-leaf-numbers/Solution.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int sumNumbers(TreeNode root, int parentval){ - - if(root == null) return 0; - - int p = parentval * 10 + root.val; - - if(root.left == null && root.right == null) return p; - - return sumNumbers(root.left, p) + sumNumbers(root.right, p); - - } - - public int sumNumbers(TreeNode root) { - return sumNumbers(root, 0); - } -} diff --git a/_includes/_root/surrounded-regions/README.md b/_includes/_root/surrounded-regions/README.md deleted file mode 100644 index dd42be8..0000000 --- a/_includes/_root/surrounded-regions/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Search from the borders - -Determine an area is surrounded by `X` is not easy, but, it is easy to know how many `O`s are connected with borders. - -Mark all `O` connected with borders, then swap the `O`s to `X`. - - -## How to konw if an `O` if it is connected with borders - - * `O` on the borders are connected with borders - * if an `O` is connected with border, `O`s on its top, bottom, left, right are connected with borders - -We can do the DFS/BFS starting from `O` on the border, mark all `O` connected with them. - - - -## Some Notes - -I first write a DFS version, but leetcode rejected because of stackoverflow. diff --git a/_includes/_root/surrounded-regions/Solution.java b/_includes/_root/surrounded-regions/Solution.java deleted file mode 100644 index c38a38b..0000000 --- a/_includes/_root/surrounded-regions/Solution.java +++ /dev/null @@ -1,101 +0,0 @@ -public class Solution { - - static class Point{ - int x; - int y; - - Point(int x, int y){ - this.x = x; - this.y = y; - } - } - - HashSet boarderConnected; - - String pointId(int x, int y){ - return x + "," + y; - } - - - // fuck stack - boolean connectIfNotConnected(char[][] board, int x, int y){ - - if(x < 0 || y < 0) return false; - if(x >= board.length || y >= board[0].length) return false; - - if(board[x][y] == 'X') return false; - - String id = pointId(x, y); - if(boarderConnected.contains(id)) return false; - - boarderConnected.add(id); - - return true; - } - - void connectBoarder(char[][] board, int x, int y){ - - - - //connectBoarder(board, x + 1, y); - //connectBoarder(board, x - 1, y); - //connectBoarder(board, x, y + 1); - //connectBoarder(board, x, y - 1); - - LinkedList queue = new LinkedList(); - - queue.add(new Point(x, y)); - - while(!queue.isEmpty()){ - Point p = queue.poll(); - - if(connectIfNotConnected(board, p.x, p.y)){ - - queue.add(new Point(p.x + 1, p.y)); - queue.add(new Point(p.x - 1, p.y)); - - queue.add(new Point(p.x, p.y + 1)); - queue.add(new Point(p.x, p.y - 1)); - } - - } - - } - - public void solve(char[][] board) { - - int mx = board.length; - if (mx < 3) return; - - int my = board[0].length; - if (my < 3) return; - - boarderConnected = new HashSet(); - - int x; - int y; - - for(x = 0; x < mx; x++){ - connectBoarder(board, x, 0); - connectBoarder(board, x, my - 1); - } - - for(y = 0; y < my; y++){ - connectBoarder(board, 0, y); - connectBoarder(board, mx - 1, y); - } - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if(board[x][y] == 'O'){ - if(!boarderConnected.contains(pointId(x, y))){ - board[x][y] = 'X'; - } - } - } - } - - - - } -} \ No newline at end of file diff --git a/_includes/_root/swap-nodes-in-pairs/README.md b/_includes/_root/swap-nodes-in-pairs/README.md deleted file mode 100644 index 909d4b0..0000000 --- a/_includes/_root/swap-nodes-in-pairs/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Recursion - - * `0 swaping` an empty linked list yields empty linked list - * `1 swaping` an one-node linked list yields one-node linked list itslef. - * `2 swaping` a two-nodes linked list yields a linked list with the original list head and tail swapped. - -So .. - - * `n swaping` a n-nodes linked list is to concat(swaping(2), swaping(n - 2)) diff --git a/_includes/_root/swap-nodes-in-pairs/Solution.java b/_includes/_root/swap-nodes-in-pairs/Solution.java deleted file mode 100644 index 3d1be6b..0000000 --- a/_includes/_root/swap-nodes-in-pairs/Solution.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public ListNode swapPairs(ListNode head) { - - - if (head == null) return null; - - if (head.next == null) return head; - - ListNode newhead = head.next; - head.next = swapPairs(head.next.next); - - newhead.next = head; - - return newhead; - - } -} \ No newline at end of file diff --git a/_includes/_root/symmetric-tree/README.md b/_includes/_root/symmetric-tree/README.md deleted file mode 100644 index b4398cd..0000000 --- a/_includes/_root/symmetric-tree/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## [Binary Tree Level Order Traversal](../binary-tree-level-order-traversal) + TreeNode version of [Valid Palindrome](../valid-palindrome) - -On each level ends, the `TreeNode`s collected should be palindromic if the tree is symmetric. - -Remember add a null node placeholder to the level collection. diff --git a/_includes/_root/symmetric-tree/Solution.java b/_includes/_root/symmetric-tree/Solution.java deleted file mode 100644 index 7c8ef60..0000000 --- a/_includes/_root/symmetric-tree/Solution.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - static final TreeNode EMPTY = new TreeNode(0); - - TreeNode nullToEmpty(TreeNode node){ - if(node == null) return EMPTY; - - return node; - } - - - public boolean isSymmetric(TreeNode root) { - - if(root == null) return true; - - LinkedList queue = new LinkedList(); - final TreeNode END = new TreeNode(0); - - LinkedList level = new LinkedList(); - - level.add(nullToEmpty(root.left)); - level.add(nullToEmpty(root.right)); - - queue.add(END); - queue.add(nullToEmpty(root.left)); - queue.add(nullToEmpty(root.right)); - - while(!queue.isEmpty()){ - - TreeNode node = queue.poll(); - - if(node == END){ - - // check - while(!level.isEmpty()){ - TreeNode left = level.pollFirst(); - TreeNode right = level.pollLast(); - - if(left == right) continue; - - if(left == EMPTY && right != EMPTY) return false; - if(left != EMPTY && right == EMPTY) return false; - - if(left.val != right.val) return false; - - } - - if(!queue.isEmpty()) queue.add(END); - - }else{ - - level.add(node); - - if(node != EMPTY){ - queue.add(nullToEmpty(node.left)); - queue.add(nullToEmpty(node.right)); - } - } - - - } - - - return true; - } -} diff --git a/_includes/_root/text-justification/README.md b/_includes/_root/text-justification/README.md deleted file mode 100644 index c6bc030..0000000 --- a/_includes/_root/text-justification/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Everyone can solve this kind of problems - -But, almost every people can not be accept in one submittion. - -A lot of edge cases, good luck. - diff --git a/_includes/_root/text-justification/Solution.java b/_includes/_root/text-justification/Solution.java deleted file mode 100644 index e8a5f15..0000000 --- a/_includes/_root/text-justification/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -public class Solution { - - String space(int len){ - char[] s = new char[len]; - Arrays.fill(s, ' '); - return new String(s); - } - - public List fullJustify(String[] words, int L) { - - ArrayList text = new ArrayList(); - - int p = 0; - int lastp = 0; - while(p < words.length){ - - if(L == 0 && "".equals(words[p])){ - text.add(""); - p++; - continue; - } - - int l = 0; - while(l < L && p < words.length){ - l += words[p++].length() + 1; - } - - if(l - 1 > L) l -= words[--p].length() + 1; - - int count = p - lastp; - int left = L - l + count; - - int add; - if(count == 1) add = left; - else if (p - 1 == words.length - 1) { add = 1; left = count - 1;} // fuck... - else add = left / ( count - 1); - - left -= add * (count - 1); - - String s = ""; - for(int i = lastp; i < p - 1; i++){ - if(left > 0){ - s += words[i] + space(add + 1); - left--; - }else{ - s += words[i] + space(add); - } - } - - left = L - s.length() - words[p - 1].length(); - - if(count == 1 || p - 1 == words.length - 1) // fuck... - s += words[p - 1] + space(left); - else - s += space(left) + words[p - 1]; - - text.add(s); - lastp = p; - } - - return text; - - } -} diff --git a/_includes/_root/trapping-rain-water/README.md b/_includes/_root/trapping-rain-water/README.md deleted file mode 100644 index 22b19ab..0000000 --- a/_includes/_root/trapping-rain-water/README.md +++ /dev/null @@ -1,230 +0,0 @@ -## Art - - -``` - +--+ - | | - +--+ | +--+ +--+ - | |WW WW WW| | |WW| | - +--+ | +--+ +--+ | +--+ +--+ - | |WW| | |WW| | | | | | | -+--+--+--+--+--+--+--+--+--+--+--+--+ - - 0 1 2 3 4 5 6 7 8 9 A B [INDEX] -``` - -## [Loop invariant](http://en.wikipedia.org/wiki/Loop_invariant) with Stack/Queue - -Sometimes, there may be an inconclusive result after a loop. you have to wait for one or more loop to merge them all to the final result. - -``` -loop - - if can merge - merge and commit all pending data to result - - else - save and wait - -``` - -In this case, when a new `bar` comes, if it is greater than or equals to all saved `bar`s, those `bar`s can make up a container. -The most important thing is that how much water the container can trap has nothing to do with later `bar`s. - - -### How much water, Bars and stones. - - - - -``` - +--+ - | | -+--+ | | -| |WW WW WW| | -| +--+ +--+ | -| | |WW| | | -+--+--+--+--+--+ - - 3 4 5 6 7 [INDEX] - -``` - -figure above show two bars with heights `2` and `3`. -so the container can trap `MIN(2,3) * (7 - 3 - 1) = 6`. - -but, wait, there are `2` stones (`Bar 4` and `Bar 6`) in the water, we should take them away. `6 - 2 = 4`. - - -``` - -// input bars are guaranteed that -// * there are more than 2 bars -// * first and last bar are the highest - -function containWater(bars) - - left = bars.first - right = bars.last - - // container - water = MIN(left.height, right.height) * (right.pos - left.pos - 1) - - // remove stone - - foreach bar in bars without first and last - water = water - bar.height - - - return water - -``` - - -### Animation - - * Bar `0` height `0` - * Water = 0 - - -``` - -Storage: - - - - - - -+--+ - 0 [INDEX] - -``` - - - * Bar `1` height `1` - * containWater(Bar `0` .. Bar `1`) = 0 - * Remove bars(Bar `0`) no longer needed - * Water = Water + 0 - * Save Bar `1` - - -``` -Storage: - - - -+--+ -| | -+--+ - 1 [INDEX] - -``` - - - * Bar `2` height `0` - * Not meet the requirement to call `containWater` (new bar's height `0` < saved bar's height `1`) - - * Bar `3` height `2` - * It is time to call `containWater` - * containWater(Bar `1` .. Bar `3`) = 1 - * Water = Water + 1 - - -``` - - - +--+ - | | -+--+ | | -| |WW| | -+--+--+--+ - 1 2 3 [INDEX] - -``` - - * Save Bar `3` - - -``` -Storage: - - -+--+ -| | -| | -| | -+--+ - 3 [INDEX] - -``` - - * Deal with Bar `3`, `4` , `5` , `6` - * Not meet the requirement to call `containWater` - * Save them - - -``` -Storage: - - +--+ - | | -+--+ | | -| |WW WW WW| | -| +--+ +--+ | -| | |WW| | | -+--+--+--+--+--+ - - 3 4 5 6 7 [INDEX] - -``` - - - * Bar `7` is the higher than any saved `Bar`, so call `containWater` - * containWater(Bar `3` .. Bar `7`) = 4 - * Water = Water + 4 - - -### Bars left in Storage - -After the loop ends, there left some bars in the storage. -From the figure below, there is `1` water in left bars. but, no bar can trigger code to call `containWater`. - - -``` -Storage: - -+--+ -| | -| +--+ +--+ -| | |WW| | -| | +--+ +--+ -| | | | | | -+--+--+--+--+--+ - - 7 8 9 A B [INDEX] -``` - - -How much water these bar can trap has nothing to do with any other bars, so we can convert the storage to a familiar question. - -Yes, just reverse it to a new one. - - -``` - +--+ - | | - +--+ +--+ | - | |WW| | | -+--+ +--+ | | -| | | | | | -+--+--+--+--+--+ - - 0 1 2 3 4 [INDEX] -``` - -Now, add trap( new one ) to water - - - - diff --git a/_includes/_root/trapping-rain-water/Solution.java b/_includes/_root/trapping-rain-water/Solution.java deleted file mode 100644 index 1cf62dd..0000000 --- a/_includes/_root/trapping-rain-water/Solution.java +++ /dev/null @@ -1,72 +0,0 @@ -public class Solution { - - static class Bar{ - int pos; - int height; - - Bar(int pos, int height){ - this.pos = pos; - this.height = height; - } - } - - int containWater(Deque queue){ - - Bar left = queue.peekFirst(); - Bar right = queue.peekLast(); - - int water = 0; - - if(right.height >= left.height){ - - water += Math.min(right.height, left.height) * (right.pos - left.pos - 1); - - queue.removeFirst(); // remove left - - // remove stones - while(queue.size() > 1){ - water -= queue.removeFirst().height; - } - } - - return water; - } - - int[] reverseAndToInt(Deque queue){ - int[] a = new int[queue.size()]; - int i = 0; - - while(!queue.isEmpty()){ - a[i++] = queue.removeLast().height; - - } - - return a; - } - - public int trap(int[] A) { - - if (A.length <= 2) return 0; - - Deque queue = new LinkedList(); - - int s = 0; - while(s < A.length && A[s] == 0) s++; - - if(s < A.length) - queue.add(new Bar(s, A[s])); - - int water = 0; - - for(int i = s + 1; i < A.length; i++){ - - queue.add(new Bar(i, A[i])); - - water += containWater(queue); - } - - water += trap(reverseAndToInt(queue)); - - return water; - } -} diff --git a/_includes/_root/triangle/README.md b/_includes/_root/triangle/README.md deleted file mode 100644 index 476ccb5..0000000 --- a/_includes/_root/triangle/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Shortest Path - -Everyone doing leetcode should know [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra's_algorithm). - -This problem is a variant of `Shortest Path`. -Start from the each point of the triangle's bottom and find the minimum path sum to the top. - -``` - -foreach level in triangle - - foreach point in level - - point_value = point_value + MIN( left connected point_value, right connected point_value) - - -top level has only 1 point -and that value is the answer - -``` - - - diff --git a/_includes/_root/triangle/Solution.java b/_includes/_root/triangle/Solution.java deleted file mode 100644 index f9d3d4d..0000000 --- a/_includes/_root/triangle/Solution.java +++ /dev/null @@ -1,27 +0,0 @@ -public class Solution { - public int minimumTotal(List> triangle) { - - final int size = triangle.size(); - if(size == 0) return 0; - if(size == 1) return triangle.get(0).get(0); - - int[] s = new int[size]; - - int i = 0; - for(int v : triangle.get(size - 1)) s[i++] = v; - - for(i = size - 2; i >=0 ; i--){ - List step = triangle.get(i); - - // s[0] = min(s[0] + step[0], s[1] + step[0]) - - for(int j = 0; j < step.size(); j++){ - s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); - } - - s[step.size()] = Integer.MAX_VALUE; - } - - return s[0]; - } -} diff --git a/_includes/_root/two-sum-ii-input-array-is-sorted/README.md b/_includes/_root/two-sum-ii-input-array-is-sorted/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java b/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java deleted file mode 100644 index bb641c2..0000000 --- a/_includes/_root/two-sum-ii-input-array-is-sorted/Solution.java +++ /dev/null @@ -1,20 +0,0 @@ -public class Solution { - public int[] twoSum(int[] numbers, int target) { - - int i = 0; - int j = numbers.length - 1; - - - while(i < j){ - if (numbers[i] + numbers[j] > target){ - j--; - }else if(numbers[i] + numbers[j] < target){ - i++; - }else { // == - return new int[]{i + 1, j + 1}; - } - } - - throw new RuntimeException(); - } -} diff --git a/_includes/_root/two-sum-iii-data-structure-design/README.md b/_includes/_root/two-sum-iii-data-structure-design/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/_includes/_root/two-sum-iii-data-structure-design/Solution.java b/_includes/_root/two-sum-iii-data-structure-design/Solution.java deleted file mode 100644 index b8a7f47..0000000 --- a/_includes/_root/two-sum-iii-data-structure-design/Solution.java +++ /dev/null @@ -1,32 +0,0 @@ -public class TwoSum { - - Map nums = new HashMap(); - - public void add(int number) { - Integer c = nums.get(number); - if(c == null) c = 0; - c++; - - nums.put(number, c); - } - - public boolean find(int value) { - - for(Integer n : nums.keySet()){ - Integer c = nums.get(value - n); - - if(c == null) continue; - - if(value - n == n){ - if(c > 1){ - return true; - } - }else{ - return true; - } - } - - - return false; - } -} diff --git a/_includes/_root/two-sum/README.md b/_includes/_root/two-sum/README.md deleted file mode 100644 index 33e5a2c..0000000 --- a/_includes/_root/two-sum/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Hello world! - -This is the first problem on leetcode. Thanks to leetcode. - diff --git a/_includes/_root/two-sum/Solution.java b/_includes/_root/two-sum/Solution.java deleted file mode 100644 index 00e561b..0000000 --- a/_includes/_root/two-sum/Solution.java +++ /dev/null @@ -1,21 +0,0 @@ -public class Solution { - public int[] twoSum(int[] numbers, int target) { - - HashMap m = new HashMap(); - - for(int i = 0; i < numbers.length; i++){ - m.put(target - numbers[i], i); - } - - for(int i = 0; i < numbers.length; i++){ - - Integer v = m.get(numbers[i]); - - if(v != null && v != i){ - return new int[]{i + 1, v + 1}; - } - } - - throw new RuntimeException(); - } -} diff --git a/_includes/_root/unique-binary-search-trees-ii/README.md b/_includes/_root/unique-binary-search-trees-ii/README.md deleted file mode 100644 index 902fe76..0000000 --- a/_includes/_root/unique-binary-search-trees-ii/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Advanced version of [Unique Binary Search Trees](../unique-binary-search-trees) - -This time, we have to collect the trees instead of counting. - -So just generate left and right, then make cartesian product of them. diff --git a/_includes/_root/unique-binary-search-trees-ii/Solution.java b/_includes/_root/unique-binary-search-trees-ii/Solution.java deleted file mode 100644 index a1aa6c2..0000000 --- a/_includes/_root/unique-binary-search-trees-ii/Solution.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; left = null; right = null; } - * } - */ -public class Solution { - - ArrayList generateTrees(int[] array){ - if (array.length == 0) return new ArrayList(Collections.singletonList(null)); - - ArrayList found = new ArrayList(); - - for(int i = 0; i < array.length; i++){ - - for(TreeNode left : generateTrees(Arrays.copyOfRange(array, 0, i))){ - for(TreeNode right : generateTrees(Arrays.copyOfRange(array, i + 1, array.length))){ - TreeNode root = new TreeNode(array[i]); - - root.left = left; - root.right = right; - - found.add(root); - } - } - } - - return found; - } - - public List generateTrees(int n) { - - int[] array = new int[n]; - - for(int i = 0; i < n ; i++) array[i] = i + 1; - - return generateTrees(array); - } -} diff --git a/_includes/_root/unique-binary-search-trees/README.md b/_includes/_root/unique-binary-search-trees/README.md deleted file mode 100644 index 8bf1658..0000000 --- a/_includes/_root/unique-binary-search-trees/README.md +++ /dev/null @@ -1,42 +0,0 @@ -## Recursion - -I solve this prolem in the toilet. - -### Review building a BST - -``` -function buildBST(nodes, root) - - root.left = buildBST(nodes that their vals are less than root.val) - root.right = buildBST(nodes that their vals are greater than or equal to root.val) - -``` - -change to numbers. - -``` -function numTrees(nodes, root) - return numTrees(nodes that their vals are less than root.val) * numTrees(nodes that their vals are greater than or equal to root.val) - -``` - -that is, there are `numTrees` on `root.left` and `numTrees` on `root.right`, so in sum just `left` times `right`. - -### How many roots - -Any number can become the root, so just add them up. - -``` -foreach node in nodes - sum = sum + numTrees(nodes, node) - -``` - - -## Empty tree - -let `numTrees(empty tree) = 1`. codes will go well. - - - - diff --git a/_includes/_root/unique-binary-search-trees/Solution.java b/_includes/_root/unique-binary-search-trees/Solution.java deleted file mode 100644 index bd693cc..0000000 --- a/_includes/_root/unique-binary-search-trees/Solution.java +++ /dev/null @@ -1,15 +0,0 @@ -public class Solution { - public int numTrees(int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(n == 0) return 1; - - int s = 0; - - for(int i = 0; i < n; i++){ - s += numTrees(i) * numTrees(n - 1 - i); - } - - return s; - } -} \ No newline at end of file diff --git a/_includes/_root/unique-paths-ii/README.md b/_includes/_root/unique-paths-ii/README.md deleted file mode 100644 index 9ceacee..0000000 --- a/_includes/_root/unique-paths-ii/README.md +++ /dev/null @@ -1,36 +0,0 @@ -## [Unique Paths](../unique-paths) with obstacle - -`1 * n` matrix - -there will be `0` unique path on the left side of an obstacle. - -``` -+---+---+---+---+---+---+---+ -| 1 | 1 | 1 | B | 0 | 0 | 0 | -+---+---+---+---+---+---+---+ -``` - -obstacle blocks the path to girds on its bottom or left. - -``` -+---+---+---+---+---+---+---+ -| 1 | 1 | 1 | B | 0 | 0 | 0 | -+---+---+---+---+---+---+---+ -| 1 | 2 | | | | | | -+---+---+---+---+---+---+---+ -| 1 | | | | B | | | -+---+---+---+---+---+---+---+ -| 1 | | | n | x | | | -+---+---+---+---+---+---+---+ -| 1 | | | | | | | -+---+---+---+---+---+---+---+ -| 1 | | | | | | | -+---+---+---+---+---+---+---+ - -``` - -in this case, `gird x` has only n paths from left grid. - - -Generally, `[x][y] = ([x - 1][y] or 0 if blocked) + ([x][y - 1] or 0 if blocked)` - diff --git a/_includes/_root/unique-paths-ii/Solution.java b/_includes/_root/unique-paths-ii/Solution.java deleted file mode 100644 index f8d2b02..0000000 --- a/_includes/_root/unique-paths-ii/Solution.java +++ /dev/null @@ -1,40 +0,0 @@ -public class Solution { - public int uniquePathsWithObstacles(int[][] obstacleGrid) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int mx = obstacleGrid.length; - int my = obstacleGrid[0].length; - - if(obstacleGrid[0][0] == 1) return 0; - if(obstacleGrid[mx - 1][my - 1] == 1) return 0; - - int x, y; - - boolean blocked = false; - for(x = 1; x < mx ; x++){ - if (obstacleGrid[x][0] == 1) blocked = true; - obstacleGrid[x][0] = blocked ? 0 : 1; - } - - blocked = false; - for(y = 1; y < my ; y++){ - if (obstacleGrid[0][y] == 1) blocked = true; - obstacleGrid[0][y] = blocked ? 0 : 1; - } - - - obstacleGrid[0][0] = 1; - - - for(x = 1; x < mx ; x++){ - for(y = 1; y < my; y++){ - if(obstacleGrid[x][y] == 1) - obstacleGrid[x][y] = 0; - else - obstacleGrid[x][y] = obstacleGrid[x - 1][y] + obstacleGrid[x][y - 1]; - } - } - - return obstacleGrid[mx - 1][my - 1]; - - } -} \ No newline at end of file diff --git a/_includes/_root/unique-paths/README.md b/_includes/_root/unique-paths/README.md deleted file mode 100644 index fb6a0ab..0000000 --- a/_includes/_root/unique-paths/README.md +++ /dev/null @@ -1,91 +0,0 @@ -## Guessing - - -`1 * 1` matrix have `1` unique path - -``` -+---+ -| 1 | -+---+ -``` - -`1 * 2` matrix have `1` unique path - -``` -+---+---+ -| 1 | 1 | -+---+---+ -``` - - -`1 * n` or `n * 1` matrix have `1` unique path - -``` -+---+---+--------- -| 1 | 1 | --> -+---+---+--------- -``` - -`2 * 2` matrix have `2` unique paths - - -``` -+---+---+ -| 1 | 1 | -+---+---+ -| 1 | 2 | -+---+---+ - -+-----+ -| | -| v -+---> - -``` - -a grid can only be entered from the grid on its top or left. - - -## Grid x - -``` -+---+---+---+---+---+---+---+ -| 1 | 1 | 1 | 1 | 1 | 1 | 1 | -+---+---+---+---+---+---+---+ -| 1 | 2 | | | | | | -+---+---+---+---+---+---+---+ -| 1 | | | | m | | | -+---+---+---+---+---+---+---+ -| 1 | | | n | x | | | -+---+---+---+---+---+---+---+ -| 1 | | | | | | | -+---+---+---+---+---+---+---+ -| 1 | | | | | | | -+---+---+---+---+---+---+---+ - -``` - -Assume that - - * from top-left to `grid m`, there are `m` unique paths - * from top-left to `grid n`, there are `n` unique paths - -So that - - * there is `m` unique paths from top-left to `grid x` via `grid m` - * there is `n` unique paths from top-left to `grid x` via `grid n` - - * there is `m + n` unique paths from top-left to `grid x` via `grid m` and `grid n` - - -## Fill up the matrix - -we can build a matrix that - - * all `[0][?] = 1` - * all `[?][0] = 1` - -fill up grids in the matrix one by one `[x][y] = [x - 1][y] + [x][y - 1]` - - -the value in the bottom-right grid is how many paths from top-left to bottom-right. diff --git a/_includes/_root/unique-paths/Solution.java b/_includes/_root/unique-paths/Solution.java deleted file mode 100644 index d8a3e36..0000000 --- a/_includes/_root/unique-paths/Solution.java +++ /dev/null @@ -1,26 +0,0 @@ -public class Solution { - public int uniquePaths(int m, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - if(m == 0 || n == 0) return 0; - - int[][] matrix = new int[m][n]; - - int x, y; - - for(x = 0; x < m; x++) - matrix[x][0] = 1; - - for(y = 0; y < n; y++) - matrix[0][y] = 1; - - - for(x = 1; x < m; x++){ - for(y = 1; y < n; y++){ - matrix[x][y] = matrix[x - 1][y] + matrix[x][y - 1]; - } - } - - return matrix[m - 1][n - 1]; - } -} \ No newline at end of file diff --git a/_includes/_root/valid-number/README.md b/_includes/_root/valid-number/README.md deleted file mode 100644 index 6510749..0000000 --- a/_includes/_root/valid-number/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## [Test-driven development](http://en.wikipedia.org/wiki/Test-driven_development) - -This is one of the lowest AC rate problems on leetcode. - -Maybe no one can cover all the edge test cases at the first time. But after a lot of submittions, everyone's code can be accepted. - -Such(k) technology is known as [Test-driven development](http://en.wikipedia.org/wiki/Test-driven_development). - diff --git a/_includes/_root/valid-number/Solution.java b/_includes/_root/valid-number/Solution.java deleted file mode 100644 index 96337f3..0000000 --- a/_includes/_root/valid-number/Solution.java +++ /dev/null @@ -1,44 +0,0 @@ -public class Solution { - - - public boolean isNumber(String s) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if ( s == null) return false; - else if( s.length() == 0 ) return false; - - char[] chars = s.toCharArray(); - int st = 0 , ed = chars.length - 1; - - while((st < ed ) && chars[st] == ' ') st++; - while((st < ed ) && chars[ed] == ' ') ed--; - - if(chars[st] == ' ') return false; - - boolean dot = false; - boolean ex = false; - boolean num = false; - - for(int i = st; i <= ed; i++ ){ - char c = chars[i]; - if ('0' <= c && c <= '9'){ - num = true; - }else if ( c == 'e'){ - if(ex) return false; - if(!num) return false; - ex = true; - num = false; - dot = false; - }else if ( c == '.'){ - if(dot) return false; - if(ex) return false; - dot = true; - }else if ( c == '-' || c == '+' ){ - if(num || dot)return false; - }else - return false; - } - - return num; - - } -} \ No newline at end of file diff --git a/_includes/_root/valid-palindrome/README.md b/_includes/_root/valid-palindrome/README.md deleted file mode 100644 index fa5d857..0000000 --- a/_includes/_root/valid-palindrome/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Two pointers - -A pointer moves from start to end, the other moves from end to start. The characters they points to should be the same. - -Note: In this problem, chars other than `[A-Za-z0-9]` should be ignored. - diff --git a/_includes/_root/valid-palindrome/Solution.java b/_includes/_root/valid-palindrome/Solution.java deleted file mode 100644 index 416312c..0000000 --- a/_includes/_root/valid-palindrome/Solution.java +++ /dev/null @@ -1,29 +0,0 @@ -public class Solution { - - boolean valid(char[] chars, int i){ - return !(('A' <= chars[i] && chars[i]<= 'Z') - || ('a' <= chars[i] && chars[i]<= 'z') - || ('0' <= chars[i] && chars[i]<= '9')); - } - - public boolean isPalindrome(String s) { - if(s == null) return false; - - char[] chars = s.toLowerCase().toCharArray(); - int i = 0, j = chars.length - 1; - - while(i < j){ - - // ignore space etc. - while( (i < j) && valid(chars, i)) i++; - while( (i < j) && valid(chars, j)) j--; - - if(chars[i] != chars[j]) return false; - - i++; - j--; - } - - return true; - } -} diff --git a/_includes/_root/valid-parentheses/README.md b/_includes/_root/valid-parentheses/README.md deleted file mode 100644 index ad9432e..0000000 --- a/_includes/_root/valid-parentheses/README.md +++ /dev/null @@ -1,24 +0,0 @@ -## Neutralization - -Using a stack to store the brackets, when a new bracket comes, test if the new one and the one on the stack's top are pairing. - -Remove the top one on the stack if they are pairing, or push the new one into stack inorder to wait further pairing. - -After all brackets are processed, there should be an empty stack if all brackets are paired. - - -``` -foreach b in brackets - - if b can pair with stack.top() - // neutralizate them - stack.pop() - else - // wait for further - stack.push(b) - - - -check if the stack is empty - -``` diff --git a/_includes/_root/valid-parentheses/Solution.java b/_includes/_root/valid-parentheses/Solution.java deleted file mode 100644 index 92af536..0000000 --- a/_includes/_root/valid-parentheses/Solution.java +++ /dev/null @@ -1,29 +0,0 @@ -public class Solution { - - boolean couple(Character l, Character r){ - if(l == null) return false; - return (l == '[' && r == ']') || (l == '(' && r == ')') || (l == '{' && r == '}'); - } - - public boolean isValid(String s) { - if(s == null) return false; - - char[] chars = s.toCharArray(); - - if(chars.length == 0 || chars.length % 2 == 1) return false; - - LinkedList stack = new LinkedList(); - - for(char c: chars){ - Character peek = stack.peek(); - - if(couple(peek, c)){ - stack.pop(); - }else{ - stack.push(c); - } - } - - return stack.size() == 0; - } -} diff --git a/_includes/_root/valid-sudoku/README.md b/_includes/_root/valid-sudoku/README.md deleted file mode 100644 index 6f216c8..0000000 --- a/_includes/_root/valid-sudoku/README.md +++ /dev/null @@ -1,19 +0,0 @@ -## Set - -`HashSet` is a data-structure that can be used for checking duplicates. - -use a `HashSet` to check if the row, column and block are valid. - -## Comments on Block checking - -here use a tricky method to convert `0..8` to `[0,0], [0,1] ... [2,2]` - -``` -for offset in 0 .. 8 - ox = offset % 3 - oy = offset / 3 -``` - -## More about Sudoku - * [Sudoku Puzzles - The Rules](http://sudoku.com.au/TheRules.aspx) - * [Sudoku on wikipedia](http://en.wikipedia.org/wiki/Sudoku) diff --git a/_includes/_root/valid-sudoku/Solution.java b/_includes/_root/valid-sudoku/Solution.java deleted file mode 100644 index 0d0a77f..0000000 --- a/_includes/_root/valid-sudoku/Solution.java +++ /dev/null @@ -1,55 +0,0 @@ -public class Solution { - public boolean isValidSudoku(char[][] board) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - int mx = board.length; - int my = board[0].length; - - int x, y; - - for(x = 0; x < mx; x++){ - HashSet col = new HashSet(); - for(y = 0; y < my; y++){ - char c = board[x][y]; - if(c != '.'){ - if(col.contains(c)) return false; - - col.add(c); - } - } - } - - for(y = 0; y < my; y++){ - HashSet row = new HashSet(); - for(x = 0; x < mx; x++){ - char c = board[x][y]; - if(c != '.'){ - if(row.contains(c)) return false; - - row.add(c); - } - } - } - - for(x = 0; x < mx; x += 3){ - for(y = 0; y < my; y += 3){ - - HashSet block = new HashSet(); - - for(int offset = 0; offset < 9; offset++){ - int ox = offset % 3; - int oy = offset / 3; - - char c = board[x + ox][y + oy]; - if(c != '.'){ - if(block.contains(c)) return false; - - block.add(c); - } - } - } - } - - return true; - } -} \ No newline at end of file diff --git a/_includes/_root/validate-binary-search-tree/README.md b/_includes/_root/validate-binary-search-tree/README.md deleted file mode 100644 index ffed955..0000000 --- a/_includes/_root/validate-binary-search-tree/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## BST property - -Inorder travel on a binary-search-tree yield values in nondecreasing order. - -So do an inorder travel on the tree, return false if there is an ascending order. diff --git a/_includes/_root/validate-binary-search-tree/Solution.java b/_includes/_root/validate-binary-search-tree/Solution.java deleted file mode 100644 index 03ab776..0000000 --- a/_includes/_root/validate-binary-search-tree/Solution.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for binary tree - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -public class Solution { - - int last; - boolean failed; - - void inorder(TreeNode root){ - - if(root == null) return; - if(failed) return; - - inorder(root.left); - - if( last >= root.val) failed = true; - last = root.val; - - inorder(root.right); - - } - - public boolean isValidBST(TreeNode root) { - // Note: The Solution object is instantiated only once and is reused by each test case. - last = Integer.MIN_VALUE; - failed = false; - - if(root == null) return true; - inorder(root); - return !failed; - } -} \ No newline at end of file diff --git a/_includes/_root/wildcard-matching/README.md b/_includes/_root/wildcard-matching/README.md deleted file mode 100644 index 565d514..0000000 --- a/_includes/_root/wildcard-matching/README.md +++ /dev/null @@ -1,62 +0,0 @@ -## Convert to [Regular Expression Matching](../regular-expression-matching) - - * `?` -> `.` - * `*` -> `.*` - -This should work, yet, it exceeds the time limited. - -## Checkpoint / Timemachine - -On modern OS, you can go back to some time you saved if your OS meets some problem. -such technology also can be used to solve this problem. - -``` - S - -[ a a b ] - -[ a * b * ] - - P - - -P is *, save current state. -``` - -`P` goes on to next - -``` - -This state means * matches nothing - - S - -[ a a b ] - -[ a * b * ] - - P - -``` - -a mismatch found, `P != S`, so rollback to checkpoint. - -``` -This state means * matches a - - S - -[ a a b ] - -[ a * b * ] - - P -``` - -Each `*` will save to a checkpoint, and retry from nothing until a match is found. - - -### Remaining tail - -Sometimes, `S` meets the end, but the `P` not. -In this case, just to check remaining chars in `P` are all `*`. diff --git a/_includes/_root/wildcard-matching/Solution.java b/_includes/_root/wildcard-matching/Solution.java deleted file mode 100644 index 62c4dd1..0000000 --- a/_includes/_root/wildcard-matching/Solution.java +++ /dev/null @@ -1,58 +0,0 @@ -public class Solution { - public boolean isMatch(String s, String p) { - - - char[] S = s.toCharArray(); - char[] P = p.toCharArray(); - - int checkpointS = -1; - int checkpointP = -1; - - int j = 0; - - for(int i = 0; i < S.length; /*void*/){ - - if(j < P.length) { - - if(S[i] == P[j] || P[j] == '?'){ - i++; - j++; - continue; - } - - if(P[j] == '*'){ - - checkpointS = i; - checkpointP = j; - - j++; - continue; - } - } - - // mismatch - - if(checkpointS >= 0){ - - checkpointS++; - - // restore - i = checkpointS; - j = checkpointP + 1; - continue; - } - - return false; - } - - while(j < P.length) { - if(P[j] == '*'){ - j++; - } else { - return false; - } - } - - return true; - } -} \ No newline at end of file diff --git a/_includes/_root/word-break-ii/README.md b/_includes/_root/word-break-ii/README.md deleted file mode 100644 index 634614d..0000000 --- a/_includes/_root/word-break-ii/README.md +++ /dev/null @@ -1,39 +0,0 @@ -## [Word Break](../word-break) with traceback - -In order to output all solutions, -just change P from `boolean` to a collection which contains all parent index. - - -``` - 0 1 2 3 4 5 6 7 8 9 A - * c a t s a n d d o g - - 0 0 3 7 - 4 - - -P[3] = [0] -P[4] = [0] - -P[7] = [3, 4] -P[10] = [7] - -``` - -## Recover strings using DFS - -To find all strings break at breakpoint, just using DFS to find out them. - - * 10, 7, 3, 0: dog sand cat - * 10, 7, 4, 0: dog and cats - -### Note: - -offsets here is 1 larger than the original offset. - -So, `7..10` here is to start form the next element, the 8th to the 11th(exclusive). - -Luckily, restore the `S[8th..11th]` is just the same as `S[7..10]`, -Because index of S starts from `0`. - - diff --git a/_includes/_root/word-break-ii/Solution.java b/_includes/_root/word-break-ii/Solution.java deleted file mode 100644 index 11df5fe..0000000 --- a/_includes/_root/word-break-ii/Solution.java +++ /dev/null @@ -1,67 +0,0 @@ -public class Solution { - - String join(List list){ - if(list.isEmpty()) return ""; - - StringBuilder s = new StringBuilder(list.get(0)); - - for(int i = 1; i < list.size(); i++){ - s.append(' '); - s.append(list.get(i)); - } - - return s.toString(); - } - - ArrayList[] P; - char[] S; - ArrayList rt; - - void joinAll(int offset, LinkedList parents){ - - if(P[offset].isEmpty()){ - - rt.add(join(parents)); - return; - } - - for(Integer p : P[offset]){ - - parents.push(new String(S, p, offset - p)); - - joinAll(p, parents); - - parents.pop(); - } - - } - - public List wordBreak(String s, Set dict) { - S = s.toCharArray(); - - P = new ArrayList[S.length + 1]; - P[0] = new ArrayList(); - - for(int i = 0; i < S.length; i++){ - for(int j = 0; j <= i; j++){ - String w = new String(S, j, i - j + 1); - if(P[j] != null && dict.contains(w)){ - - if(P[i + 1] == null){ - P[i + 1] = new ArrayList(); - } - - P[i + 1].add(j); - } - } - } - - rt = new ArrayList(); - - if(P[S.length] != null){ - joinAll(S.length, new LinkedList()); - } - - return rt; - } -} diff --git a/_includes/_root/word-break/README.md b/_includes/_root/word-break/README.md deleted file mode 100644 index 479187c..0000000 --- a/_includes/_root/word-break/README.md +++ /dev/null @@ -1,41 +0,0 @@ -## All break - -Brute force is my favourite. However, `2 ^ n` seems a huge number. - - -## Something like [Jump Game II](../jump-game-ii) - -That `s[0..i]` can be `break` indicates `s[i + each d in dict]` can be `break`. - -Make a table `P`, such that, `P[i]` means if `s[0..i]` can be `break`. - -``` -dict { leet, code } - -Table: - - 0 1 2 3 4 5 6 7 8 Index - * l e e t c o d e - 1 0 0 0 1 0 0 0 1 - -``` - -Calculating `P[i]` - -``` -dict { leet, code } - -Table: - - 0 1 2 3 4 5 6 7 8 Index - * l e e t c o d e - 1 0 0 0 1 ? ? ? ? - ^ - i -``` - -here if `P[i]` wants to be true, either `s[0..i]` `(leetc)` or `s[4..i]` `(c)` must be in the dict. - -So, - -`P[i] = P[0..j] && s[j..i] in dict, j = 0..i` diff --git a/_includes/_root/word-break/Solution.java b/_includes/_root/word-break/Solution.java deleted file mode 100644 index ddb0b2c..0000000 --- a/_includes/_root/word-break/Solution.java +++ /dev/null @@ -1,23 +0,0 @@ -public class Solution { - public boolean wordBreak(String s, Set dict) { - - char[] S = s.toCharArray(); - - boolean[] P = new boolean[S.length + 1]; - P[0] = true; - - for(int i = 0; i < S.length; i++){ - - for(int j = 0; j <= i; j++){ - if(P[j] && dict.contains(new String(S, j, i - j + 1))){ - P[i + 1] = true; - continue; - } - } - } - - return P[S.length]; - - - } -} \ No newline at end of file diff --git a/_includes/_root/word-ladder-ii/README.md b/_includes/_root/word-ladder-ii/README.md deleted file mode 100644 index 142ae72..0000000 --- a/_includes/_root/word-ladder-ii/README.md +++ /dev/null @@ -1,35 +0,0 @@ -## Nightmare version of [Word Ladder](../word-ladder) - - * Trace back - - In this case you need to output the path, so we need to rememeber the path using something like linked list. - - * Break after first meet the end - - I did not notice that the prolem is asking that `find all shortest transformation sequence(s) from start to end`. - I try to ouput all the transformation, and I got a time limited. - - * Duplicates blocking - - Since we need to output all the transformations, we can NOT block the connected words as soon as we meet them. - The blocked words would take effect at next level. - - - Bad case - -``` -"red", "tax", ["ted","tex","red","tax","tad","den","rex","pee"] - - -Queue Item - -[ -"red" -> "ted", -"red" -> "rex" -] - -``` - -The first item `"red" -> "ted"` poll from queue and became `"red" -> "ted" -> "tex"`, If we block `"tex"` immediately, the `"red" -> "rex" -> "tex"` will be lost. - -As a result, we should delay blocking `"tex"` until next level. diff --git a/_includes/_root/word-ladder-ii/Solution.java b/_includes/_root/word-ladder-ii/Solution.java deleted file mode 100644 index 9243888..0000000 --- a/_includes/_root/word-ladder-ii/Solution.java +++ /dev/null @@ -1,136 +0,0 @@ -public class Solution { - - static class Word { - - String word; - Set next; - - boolean end; - - Word(String word){ - this.word = word; - } - } - - static class Trace { - - Word obj; - Trace prev; - - Trace(Word obj,Trace prev){ - this.obj = obj; - this.prev = prev; - } - } - - - HashMap wmap; - - void connect(Word w, Set dict){ - if(w.next != null) return; - - Set n = new HashSet(); - - char[] ws = w.word.toCharArray(); - - for(int i = 0; i < ws.length; i++){ - char t = ws[i]; - - for(char r = 'a'; r <= 'z'; r++){ - ws[i] = r; - - String d = new String(ws); - if(dict.contains(d)){ - Word c = wmap.get(d); - n.add(c); - } - } - - ws[i] = t; - } - - w.next = n; - } - - - public List> findLadders(String start, String end, Set dict) { - - - List> rt = new ArrayList>(); - - wmap = new HashMap(); - - for(String d : dict){ - Word w = new Word(d); - wmap.put(d, w); - } - - Word _end = new Word(end); - _end.end = true; - wmap.put(end, _end); - - // help to connected to end - dict.add(end); - - - final Trace SEP = new Trace(null, null); - LinkedList queue = new LinkedList(); - - queue.add(new Trace(new Word(start), null)); - queue.add(SEP); - - boolean found = false; - - HashSet vi = new HashSet(); - HashSet svi = new HashSet(); - - while(!queue.isEmpty()){ - - Trace step = queue.poll(); - - if(step == SEP) { - vi.addAll(svi); - svi.clear(); - - if (found) break; - if (!queue.isEmpty()) queue.add(SEP); - - } else { - - Word word = step.obj; - connect(word, dict); - - - if(word.end){ - - LinkedList r = new LinkedList(); - - - Trace t = step; - - while (t != null){ - r.addFirst(t.obj.word); - t = t.prev; - } - - rt.add(r); - - found = true; - - }else if(!found){ // prevent deeper level to be visited - - for (Word p : word.next) { - - if(!vi.contains(p)) { - queue.add(new Trace(p, step)); - svi.add(p); - } - } - } - } - } - - - return rt; - } -} diff --git a/_includes/_root/word-ladder/README.md b/_includes/_root/word-ladder/README.md deleted file mode 100644 index d0e5739..0000000 --- a/_includes/_root/word-ladder/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## [Breadth-first search](http://en.wikipedia.org/wiki/Breadth-first_search) - -Finding the shortest path via BFS. - - * a level counter, plus one when level ends - * find a word in `dict` that can be jumped to, add it into queue - * using something like a set to keep the visited path away. - -## Time Limited Note: - -At first, I use an `isConnected` function to check if every word in `dict` connected to current word, -obviously, it will take `O(len(dict))` time. - -Some testcases on leetcode have a very large dict, my code fail. - -Then, I change to an `O(len(word))` time method, that is to replace each char in the current word and check if it is in the `dict`. -This way help me pass the testcases. diff --git a/_includes/_root/word-ladder/Solution.java b/_includes/_root/word-ladder/Solution.java deleted file mode 100644 index ce069f3..0000000 --- a/_includes/_root/word-ladder/Solution.java +++ /dev/null @@ -1,59 +0,0 @@ -public class Solution { - - public int ladderLength(String start, String end, Set dict) { - - LinkedList queue = new LinkedList(); - final String END = new String(); - - queue.add(start); - queue.add(END); - - int level = 0; - HashSet vi = new HashSet(); - - while(!queue.isEmpty()){ - - String current = queue.poll(); - - if(current == END){ - level++; - - if(!queue.isEmpty()) queue.add(END); - }else{ - - if(end.equals(current)) - return level + 1; - - char[] word = current.toCharArray(); - - for(int i = 0; i < word.length; i++){ - - char old = word[i]; - - for(char j = 'a'; j <= 'z' ; j++){ - - if(j == old) - continue; - - word[i] = j; - - String s = new String(word); - - if(dict.contains(s) && !vi.contains(s)){ - queue.add(s); - vi.add(s); - } - - } - - word[i] = old; - } - - } - - } - - return 0; - - } -} diff --git a/_includes/_root/word-search/README.md b/_includes/_root/word-search/README.md deleted file mode 100644 index f88043e..0000000 --- a/_includes/_root/word-search/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Apply DFS pattern - -See DFS pattern in [N-Queens](../n-queens) - - * `steps`: all chars in the word - * `choices each step`: jump to the grid on up, down, left or right - * `possibility checker`: the char in target grid is the same as the next step char - - -Start a DFS word search on each grid if it has the same char as the first char of `word`. -If any of them matches the word, stop and return `true`. diff --git a/_includes/_root/word-search/Solution.java b/_includes/_root/word-search/Solution.java deleted file mode 100644 index ec307f3..0000000 --- a/_includes/_root/word-search/Solution.java +++ /dev/null @@ -1,85 +0,0 @@ -public class Solution { - - class XY{ - int x; - int y; - - XY(int x, int y) { - this.x = x; - this.y = y; - } - } - - XY[] stack; - - int mx; - int my; - - boolean search(char[][] board, char[] cs, final int index){ - - if(index >= cs.length) return true; - - // final int mx = board.length, my = board[0].length; - - final int x = stack[index - 1].x, y = stack[index - 1].y; - - next: - for(XY xy : new XY[]{new XY(x - 1, y), new XY(x + 1, y), new XY(x, y - 1), new XY(x, y + 1) }){ - int _x = xy.x; - int _y = xy.y; - - for(int i = 0; i < index ; i++){ - if(stack[i].x == _x && stack[i].y == _y) - continue next; - } - - if(_x >=0 && _x < mx && _y >= 0 && _y < my){ - if(board[_x][_y] == cs[index]){ - stack[index] = new XY(_x , _y); - - if(search(board, cs, index + 1)) - return true; - } - } - - } - - return false; - } - - - public boolean exist(char[][] board, String word) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - if (board.length == 0) return false; - - - int x = 0, y = 0; - - mx = board.length; - my = board[0].length; - - char[] str = word.toCharArray(); - - - //if( str.length > mx * my ) return false; // fuck.. - - stack = new XY[str.length]; - - if(str.length == 0) return false; - - for(x = 0; x < mx; x++){ - for(y = 0; y < my; y++){ - if( board[x][y] == str[0] ){ - - stack[0] = new XY(x, y); - if(search(board, str, 1)) - return true; - } - } - } - - return false; - } -} \ No newline at end of file diff --git a/_includes/_root/zigzag-conversion/README.md b/_includes/_root/zigzag-conversion/README.md deleted file mode 100644 index ee561b6..0000000 --- a/_includes/_root/zigzag-conversion/README.md +++ /dev/null @@ -1,15 +0,0 @@ -## Simulating - -Create a fake paper, write every character on it. - -``` - * * * - * * * * - * * * * - * * - |r-2+1| - - col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) -``` - -paper's area is `col` * `row`. diff --git a/_includes/_root/zigzag-conversion/Solution.java b/_includes/_root/zigzag-conversion/Solution.java deleted file mode 100644 index 63ef178..0000000 --- a/_includes/_root/zigzag-conversion/Solution.java +++ /dev/null @@ -1,56 +0,0 @@ -public class Solution { - public String convert(String s, int nRows) { - // Note: The Solution object is instantiated only once and is reused by each test case. - - //row = 4 - /* - * * * - * * * * - * * * * - * * - |r-2+1| - - col = (row - 2 + 1) * (len(s) / (row + row - 2) + 1) - */ - - if(nRows == 1) return s; - - int nCols = (nRows - 2 + 1) * (s.length() / (nRows + nRows - 2) + 1); - char[][] paper = new char[nCols][nRows]; - - //int ps = 0; - char[] str = s.toCharArray(); - - int pr = 0, pc = 0; - - boolean direction = false; // true for down false for up , start up = come from up - - - for(char c : str){ - paper[pc][pr] = c; - - if(pr == 0 || pr == nRows - 1){ - direction = !direction; - } - - if(direction){ - pr++; - }else{ - pr--; - pc++; - } - } - - String rt = ""; - for(int i = 0; i < nRows; i++){ - for(int j = 0; j < nCols; j++){ - if(paper[j][i] != 0){ - rt += paper[j][i]; - } - } - } - - return rt; - - } -} \ No newline at end of file diff --git a/_layouts/solution.html b/_layouts/solution.html index 40448c2..cb0676c 100644 --- a/_layouts/solution.html +++ b/_layouts/solution.html @@ -10,7 +10,7 @@
-

{{ page.title }}

+

[leetcode] {{ page.title }}

{{leetcode_url}}

Last Update {{ page.date }} View on Github

From 6b0096b718a6008dce0b6b9be9fba09d15dfd773 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:42:14 +0800 Subject: [PATCH 055/195] add leetcode to page title --- _includes/head.html | 2 +- _layouts/solution.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/_includes/head.html b/_includes/head.html index c8f1016..58833a7 100644 --- a/_includes/head.html +++ b/_includes/head.html @@ -1,7 +1,7 @@ - {% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %} + [leetcode]{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %} diff --git a/_layouts/solution.html b/_layouts/solution.html index cb0676c..40448c2 100644 --- a/_layouts/solution.html +++ b/_layouts/solution.html @@ -10,7 +10,7 @@
-

[leetcode] {{ page.title }}

+

{{ page.title }}

{{leetcode_url}}

Last Update {{ page.date }} View on Github

From ca4efcd1fc54ebec737df5627202756c839e654c Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:47:47 +0800 Subject: [PATCH 056/195] make_shadow is no longer need --- make_shadow.sh | 9 --------- 1 file changed, 9 deletions(-) delete mode 100755 make_shadow.sh diff --git a/make_shadow.sh b/make_shadow.sh deleted file mode 100755 index 8209713..0000000 --- a/make_shadow.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -for f in `ls -d */`;do - if [ -f $f/Solution.java ];then - mkdir -p _includes/_root/$f - /bin/cp -r $f/Solution.java _includes/_root/$f/Solution.java - /bin/cp -r $f/README.md _includes/_root/$f/README.md - fi -done From 2a66d5b120b516646d3236653b2823ac479e6234 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:53:16 +0800 Subject: [PATCH 057/195] update modify time --- anagrams/index.md | 2 +- largest-number/index.md | 2 +- reverse-words-in-a-string/index.md | 2 +- sqrtx/index.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/anagrams/index.md b/anagrams/index.md index 3a959e4..bd03345 100644 --- a/anagrams/index.md +++ b/anagrams/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Anagrams -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-18 23:39:27 +0800 leetcode_id: 49 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/largest-number/index.md b/largest-number/index.md index f771171..f665df4 100644 --- a/largest-number/index.md +++ b/largest-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Largest Number -date: 2015-01-14 11:09:14 +0800 +date: 2015-01-19 00:17:27 +0800 leetcode_id: 179 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-words-in-a-string/index.md b/reverse-words-in-a-string/index.md index 0de130d..88bd05e 100644 --- a/reverse-words-in-a-string/index.md +++ b/reverse-words-in-a-string/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Words in a String -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-19 00:08:01 +0800 leetcode_id: 151 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sqrtx/index.md b/sqrtx/index.md index 2ef4d1a..31cc78c 100644 --- a/sqrtx/index.md +++ b/sqrtx/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sqrt(x) -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-18 23:48:07 +0800 leetcode_id: 69 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From b7e98e1b87696540fc39d0754e213bdba940cd82 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 00:59:51 +0800 Subject: [PATCH 058/195] try sym link --- .gitmodules | 4 ---- _includes/_root | 1 - 2 files changed, 5 deletions(-) delete mode 100644 .gitmodules delete mode 160000 _includes/_root diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index a5b4b4f..0000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "_includes/_root"] - path = _includes/_root - url = https://github.com/tg123/leetcode.git - branch = gh-pages diff --git a/_includes/_root b/_includes/_root deleted file mode 160000 index a2df120..0000000 --- a/_includes/_root +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a2df1209cc0d85bdc827cb7a22b9dbafd4a2ccc0 From 7e1db4740d6c537d241654063553e48a25d6f8cc Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 01:00:15 +0800 Subject: [PATCH 059/195] try sym link --- _includes/_root | 1 + 1 file changed, 1 insertion(+) create mode 120000 _includes/_root diff --git a/_includes/_root b/_includes/_root new file mode 120000 index 0000000..a96aa0e --- /dev/null +++ b/_includes/_root @@ -0,0 +1 @@ +.. \ No newline at end of file From d60e3b029e115e2c4d3c87cc7580ebf800764420 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 01:10:02 +0800 Subject: [PATCH 060/195] try sym link again --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index a96aa0e..b870225 120000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -.. \ No newline at end of file +../ \ No newline at end of file From 6ce96ecc5960f6052a905402cbbedfc8993665a2 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 01:13:28 +0800 Subject: [PATCH 061/195] try sub module --- _includes/.gitmodules | 4 ++++ _includes/_root | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 _includes/.gitmodules delete mode 120000 _includes/_root diff --git a/_includes/.gitmodules b/_includes/.gitmodules new file mode 100644 index 0000000..bfb7670 --- /dev/null +++ b/_includes/.gitmodules @@ -0,0 +1,4 @@ +[submodule "_includes/_root"] + path = _includes/_root + url = https://github.com/tg123/leetcode.git + branch = gh-pages diff --git a/_includes/_root b/_includes/_root deleted file mode 120000 index b870225..0000000 --- a/_includes/_root +++ /dev/null @@ -1 +0,0 @@ -../ \ No newline at end of file From 5850ca181b24490dda61576de0bc956af395f058 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 19 Jan 2015 01:17:11 +0800 Subject: [PATCH 062/195] try submodule --- _includes/.gitmodules => .gitmodules | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename _includes/.gitmodules => .gitmodules (100%) diff --git a/_includes/.gitmodules b/.gitmodules similarity index 100% rename from _includes/.gitmodules rename to .gitmodules From 0609bbc5911dcba2cae4fdee22e936145186b929 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:16:46 +0800 Subject: [PATCH 063/195] add two sum sorted doc --- two-sum-ii-input-array-is-sorted/README.md | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/two-sum-ii-input-array-is-sorted/README.md b/two-sum-ii-input-array-is-sorted/README.md index e69de29..dbd6eda 100644 --- a/two-sum-ii-input-array-is-sorted/README.md +++ b/two-sum-ii-input-array-is-sorted/README.md @@ -0,0 +1,53 @@ +## Turning + +Think you are cooking a soup, you need to add salt when taste light or add water if salty. + +However, there are two factors. + +`x + y > target` + + * decrease x + * decrease y + + +`x + y < target` + + * increase x + * increase y + +make `x` the minimum and `y` the maximum, then only one way to solve the problem. + +`x + y > target` + + * decrease x + * decrease y + + +`x + y < target` + + * increase x + * increase y + + + code might be like + + ``` + + x = first + y = last + + while num[x] + num[y] != target + + if num[x] + num[y] > target + y = y - 1 + + if num[x] + num[y] < target + x = x + 1 + + ``` + + Notes: + + Q: Why not `x--` when `num[x] + num[y] > target` ? + + A: value of `x - 1` and `y` had already tested. From d147c6403bde9bc665b8dd8857f5c9a3a2616875 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:19:58 +0800 Subject: [PATCH 064/195] surrenderrrrrrrrrr --- .gitmodules | 4 ++-- _includes/_root | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) create mode 160000 _includes/_root diff --git a/.gitmodules b/.gitmodules index bfb7670..3fdb97a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "_includes/_root"] - path = _includes/_root - url = https://github.com/tg123/leetcode.git + path = _includes/_root + url = https://github.com/tg123/leetcode.git branch = gh-pages diff --git a/_includes/_root b/_includes/_root new file mode 160000 index 0000000..0609bbc --- /dev/null +++ b/_includes/_root @@ -0,0 +1 @@ +Subproject commit 0609bbc5911dcba2cae4fdee22e936145186b929 From a9195cf52f40ffed54eba8cea6d61772755b9a31 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:26:33 +0800 Subject: [PATCH 065/195] add compare version number --- compare-version-numbers/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compare-version-numbers/README.md b/compare-version-numbers/README.md index e69de29..960216f 100644 --- a/compare-version-numbers/README.md +++ b/compare-version-numbers/README.md @@ -0,0 +1,4 @@ +## Split and compare + + * split by '*' into parts + * compare each part from the left to the right From 5a1517a1c217ba92ffd64b1966b01058bacb41bd Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:33:39 +0800 Subject: [PATCH 066/195] add largest number doc --- largest-number/README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/largest-number/README.md b/largest-number/README.md index e69de29..0c6267b 100644 --- a/largest-number/README.md +++ b/largest-number/README.md @@ -0,0 +1,24 @@ +## Sort and join + +``` +[3, 30, 34, 5, 9] + +sort into + +[9, 5, 34, 3, 30] +``` + +So, the problem is what is the sorting factor? + +### Why `3` > `30` ? + +just `brute force`. + +`3` + `30` (`330`) > `30` + `3` (`303`) + +In general, `x` > `y` when `xy` > `yx`. + + +Notes: + +In my code using `.sorted((x, y) -> (y + x).compareTo(x + y))` is because I want a non-ascending order result. From 829fc56570e8da875071b625686c2dff919a2874 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:46:10 +0800 Subject: [PATCH 067/195] add fraction to recurring dec doc --- fraction-to-recurring-decimal/README.md | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/fraction-to-recurring-decimal/README.md b/fraction-to-recurring-decimal/README.md index e69de29..842fd24 100644 --- a/fraction-to-recurring-decimal/README.md +++ b/fraction-to-recurring-decimal/README.md @@ -0,0 +1,26 @@ +## Simulating division on paper + +Pic from [Wikipedia](http://en.wikipedia.org/wiki/Repeating_decimal#Decimal_expansion_and_recurrence_sequence) + +``` + . . + 0.0675 + _______ + 74 ) 5.00000 + 4.44 + _______ + 560 + 518 + _____ + 420 + 370 + ____ + 500 +``` + +### When to stop? + +Have a look at at the pic above, when we see `500` we are sure that the next `quotient` is `6`. +Because we had calculated `500 / 74` before. + +What we need is to remember and check if the `quotient` has been done once before. From 23efa3e3cf94fbf2600dc7a2382ec567a5102042 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:53:50 +0800 Subject: [PATCH 068/195] add excel sheeeet doc --- excel-sheet-column-title/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/excel-sheet-column-title/README.md b/excel-sheet-column-title/README.md index e69de29..5ee80a3 100644 --- a/excel-sheet-column-title/README.md +++ b/excel-sheet-column-title/README.md @@ -0,0 +1,3 @@ +## [The bijective base-26 system](http://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system) + +see also [Excel Sheet Column Number](../excel-sheet-column-number) From db5895908e85e567ebaafa8fcce80480f6758c8d Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 17:54:45 +0800 Subject: [PATCH 069/195] add excel sheet doc --- excel-sheet-column-number/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/excel-sheet-column-number/README.md b/excel-sheet-column-number/README.md index e69de29..8848cfb 100644 --- a/excel-sheet-column-number/README.md +++ b/excel-sheet-column-number/README.md @@ -0,0 +1,3 @@ +## [The bijective base-26 system](http://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system) + +see also [Excel Sheet Column Title](../excel-sheet-column-title) From c6b636725f5f55fc5d7624d652d87d089808a711 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 18:05:09 +0800 Subject: [PATCH 070/195] add two sum data struct --- two-sum-iii-data-structure-design/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/two-sum-iii-data-structure-design/README.md b/two-sum-iii-data-structure-design/README.md index e69de29..4b33f27 100644 --- a/two-sum-iii-data-structure-design/README.md +++ b/two-sum-iii-data-structure-design/README.md @@ -0,0 +1,13 @@ +## [Two Sum](../two-sum) with data structure + +We can do [Two Sum](../two-sum) using + + * search `O(n * n)` times with no extra spaces + * search `O(n)` times with `O(n)` extra spaces + * sort `O(n lg n)` and search `O(n)` times. see [Two Sum II - Input array is sorted](../two-sum-ii-input-array-is-sorted) + +A small modification to `O(n)` version would get a + + * `O(1) find` + * `O(1) add` + * `O(n) space` From 15f0e9eebac4be98301c79641656799790ef8b61 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 18:54:25 +0800 Subject: [PATCH 071/195] add wow game doc --- dungeon-game/README.md | 90 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/dungeon-game/README.md b/dungeon-game/README.md index e69de29..b931df8 100644 --- a/dungeon-game/README.md +++ b/dungeon-game/README.md @@ -0,0 +1,90 @@ +## Knight on the [Unique Paths II](../unique-paths-ii) + +Same problem as [Unique Paths II](../unique-paths-ii). Only different is to walk from end to start. + + +The Dungeon + +``` ++-----+-----+-----+ +| -2 | -3 | 3 | A ++-----+-----+-----+ +| -5 | -10 | 1 | B ++-----+-----+-----+ +| 10 | 30 | -5 | C ++-----+-----+-----+ + + 1 2 3 +``` + +### The minimum health when the Knight reach the final Boss + +Let make a table. + +final room need `1 - (-5) = 6` HP (`hp - 5 = 1` to survive) + +``` ++-----+-----+-----+ +| | | | A ++-----+-----+-----+ +| | | | B ++-----+-----+-----+ +| | | 6 | C ++-----+-----+-----+ + + 1 2 3 +``` + +the Knight can enter the final room from either `C2` or `B3`. + +in `C2` he can got `30` HP, so if he could reach `C2` then he can enter the final room. So he only need to survive (`1 HP`). +`1 + 30 > 6`. + +in `B3` he will get `1` HP. the Knight will need `5 (6 - 1)` HP to reach the final room. + +``` ++-----+-----+-----+ +| | | | A ++-----+-----+-----+ +| | | 5 | B ++-----+-----+-----+ +| | 1 | 6 | C ++-----+-----+-----+ + + 1 2 3 +``` + +in `B2`, the Knigth need `11 (1 - (-10))` HP to reach `C2` and `15 (5 - (-10)) to reach `B3`. + +If I were the Knight i would enter `C2` because it requires less HP. `B2 = MIN(11, 15)` + +``` ++-----+-----+-----+ +| | | | A ++-----+-----+-----+ +| | 11 | 5 | B ++-----+-----+-----+ +| | 1 | 6 | C ++-----+-----+-----+ + + 1 2 3 +``` + + +In gerneral, HPNeed[x][y] = MIN(HPNeed[x + 1][y] - D[x][y], HPNeed[x][y + 1] - D[x][y]). + +Sometimes, the HPNeed[x][y] might go below zero, like `C2` <- `C3`, that means `1 HP` is OK. + +The work is to fill up the table, and the first cell is the answer. + +``` ++-----+-----+-----+ +| 7 | 5 | 2 | A ++-----+-----+-----+ +| 6 | 11 | 5 | B ++-----+-----+-----+ +| 1 | 1 | 6 | C ++-----+-----+-----+ + + 1 2 3 +``` From 76474de4933eea831b59afda23e6d2cb20a70df3 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 18:55:52 +0800 Subject: [PATCH 072/195] update time modified --- compare-version-numbers/index.md | 2 +- dungeon-game/index.md | 2 +- excel-sheet-column-number/index.md | 2 +- excel-sheet-column-title/index.md | 2 +- fraction-to-recurring-decimal/index.md | 2 +- largest-number/index.md | 2 +- two-sum-ii-input-array-is-sorted/index.md | 2 +- two-sum-iii-data-structure-design/index.md | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compare-version-numbers/index.md b/compare-version-numbers/index.md index dccffb1..0273b92 100644 --- a/compare-version-numbers/index.md +++ b/compare-version-numbers/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Compare Version Numbers -date: 2014-12-17 06:37:52 +0800 +date: 2015-01-21 17:26:33 +0800 leetcode_id: 165 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/dungeon-game/index.md b/dungeon-game/index.md index 59d949e..a4fc3bc 100644 --- a/dungeon-game/index.md +++ b/dungeon-game/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Dungeon Game -date: 2015-01-07 03:58:50 +0800 +date: 2015-01-21 18:54:25 +0800 leetcode_id: 174 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/excel-sheet-column-number/index.md b/excel-sheet-column-number/index.md index 4de8576..9f7aaed 100644 --- a/excel-sheet-column-number/index.md +++ b/excel-sheet-column-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Excel Sheet Column Number -date: 2014-12-28 23:11:22 +0800 +date: 2015-01-21 17:54:45 +0800 leetcode_id: 171 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/excel-sheet-column-title/index.md b/excel-sheet-column-title/index.md index 584735a..4806a7f 100644 --- a/excel-sheet-column-title/index.md +++ b/excel-sheet-column-title/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Excel Sheet Column Title -date: 2014-12-20 23:39:15 +0800 +date: 2015-01-21 17:53:50 +0800 leetcode_id: 168 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/fraction-to-recurring-decimal/index.md b/fraction-to-recurring-decimal/index.md index 9a58b04..813fdef 100644 --- a/fraction-to-recurring-decimal/index.md +++ b/fraction-to-recurring-decimal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Fraction to Recurring Decimal -date: 2014-12-17 06:40:20 +0800 +date: 2015-01-21 17:46:10 +0800 leetcode_id: 166 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/largest-number/index.md b/largest-number/index.md index f665df4..82c2ac1 100644 --- a/largest-number/index.md +++ b/largest-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Largest Number -date: 2015-01-19 00:17:27 +0800 +date: 2015-01-21 17:33:39 +0800 leetcode_id: 179 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/two-sum-ii-input-array-is-sorted/index.md b/two-sum-ii-input-array-is-sorted/index.md index 2a71780..fcfb357 100644 --- a/two-sum-ii-input-array-is-sorted/index.md +++ b/two-sum-ii-input-array-is-sorted/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum II - Input array is sorted -date: 2014-12-20 23:39:15 +0800 +date: 2015-01-21 17:16:46 +0800 leetcode_id: 167 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/two-sum-iii-data-structure-design/index.md b/two-sum-iii-data-structure-design/index.md index f541dc6..56f45d1 100644 --- a/two-sum-iii-data-structure-design/index.md +++ b/two-sum-iii-data-structure-design/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum III - Data structure design -date: 2014-12-26 18:08:59 +0800 +date: 2015-01-21 18:05:09 +0800 leetcode_id: 170 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 494919988883bc77941a465294ff6c353b3408af Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 21 Jan 2015 18:56:35 +0800 Subject: [PATCH 073/195] update gh-pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 0609bbc..76474de 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 0609bbc5911dcba2cae4fdee22e936145186b929 +Subproject commit 76474de4933eea831b59afda23e6d2cb20a70df3 From f50ba009e26d01092bc5cc7926c2adb2da93c86e Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 22 Jan 2015 01:52:46 +0800 Subject: [PATCH 074/195] update var name --- sort-colors/Solution.java | 44 +++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/sort-colors/Solution.java b/sort-colors/Solution.java index 3749c0e..3c1ada5 100644 --- a/sort-colors/Solution.java +++ b/sort-colors/Solution.java @@ -1,36 +1,36 @@ public class Solution { + + void swap(int[] A, int i, int j){ + int t = A[i]; + A[i] = A[j]; + A[j] = t; + } + public void sortColors(int[] A) { - // Note: The Solution object is instantiated only once and is reused by each test case. - int red = 0; + int red = 0; int blue = A.length - 1; - int p = 0; - - int t = 0; + int white = 0; - while(p <= blue){ + while( white <= blue ){ + + if(A[white] == 0){ // red + swap(A, white, red); - if(A[p] == 0){ //red - t = A[p]; - A[p] = A[red]; - A[red] = t; - red++; - p++; + white++; + }else if(A[white] == 1){ // white - }else if(A[p] == 2){ // blue - t = A[p]; - A[p] = A[blue]; - A[blue] = t; + white++; - blue--; - }else{ // white - - p++; + }else if (A[white] == 2) { //blue + + swap(A, white, blue); + blue--; } - } + } -} \ No newline at end of file +} From 258fc9c77500f42e49f34034db4ca4195837c93a Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 23 Jan 2015 12:45:49 +0800 Subject: [PATCH 075/195] Update README.md --- two-sum-ii-input-array-is-sorted/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum-ii-input-array-is-sorted/README.md b/two-sum-ii-input-array-is-sorted/README.md index dbd6eda..53860ba 100644 --- a/two-sum-ii-input-array-is-sorted/README.md +++ b/two-sum-ii-input-array-is-sorted/README.md @@ -1,4 +1,4 @@ -## Turning +## Tuning Think you are cooking a soup, you need to add salt when taste light or add water if salty. From 960a6271b83c67612ff2a14d017e0778a9cd94bb Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 29 Jan 2015 15:17:38 +0800 Subject: [PATCH 076/195] add ref to guava --- simplify-path/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/simplify-path/README.md b/simplify-path/README.md index fd638b9..34e28e3 100644 --- a/simplify-path/README.md +++ b/simplify-path/README.md @@ -46,3 +46,5 @@ foreach dirname in reverse order ``` +## See a [Google version libguava](https://github.com/google/guava/blob/v18.0/guava/src/com/google/common/io/Files.java#L718) + From 68206d631e8ae1ea3581b808798a23ab0d4a8235 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 29 Jan 2015 16:42:02 +0800 Subject: [PATCH 077/195] update modify time --- _includes/_root | 2 +- simplify-path/index.md | 2 +- sort-colors/index.md | 2 +- two-sum-ii-input-array-is-sorted/index.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/_includes/_root b/_includes/_root index 76474de..960a627 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 76474de4933eea831b59afda23e6d2cb20a70df3 +Subproject commit 960a6271b83c67612ff2a14d017e0778a9cd94bb diff --git a/simplify-path/index.md b/simplify-path/index.md index 5a984c4..cd0d98a 100644 --- a/simplify-path/index.md +++ b/simplify-path/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Simplify Path -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-29 15:17:38 +0800 leetcode_id: 71 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/sort-colors/index.md b/sort-colors/index.md index 289bdca..81eaad5 100644 --- a/sort-colors/index.md +++ b/sort-colors/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Sort Colors -date: 2014-12-29 00:26:24 +0800 +date: 2015-01-22 01:52:46 +0800 leetcode_id: 75 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/two-sum-ii-input-array-is-sorted/index.md b/two-sum-ii-input-array-is-sorted/index.md index fcfb357..fd0423c 100644 --- a/two-sum-ii-input-array-is-sorted/index.md +++ b/two-sum-ii-input-array-is-sorted/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Two Sum II - Input array is sorted -date: 2015-01-21 17:16:46 +0800 +date: 2015-01-23 12:45:49 +0800 leetcode_id: 167 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 1c3e913d946a8d53c76f4065299c5e2c12599fdf Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 3 Feb 2015 14:42:33 +0800 Subject: [PATCH 078/195] add reverse words ii --- reverse-words-in-a-string-ii/README.md | 0 reverse-words-in-a-string-ii/Solution.java | 30 ++++++++++++++++++++++ reverse-words-in-a-string-ii/index.md | 9 +++++++ 3 files changed, 39 insertions(+) create mode 100644 reverse-words-in-a-string-ii/README.md create mode 100644 reverse-words-in-a-string-ii/Solution.java create mode 100644 reverse-words-in-a-string-ii/index.md diff --git a/reverse-words-in-a-string-ii/README.md b/reverse-words-in-a-string-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/reverse-words-in-a-string-ii/Solution.java b/reverse-words-in-a-string-ii/Solution.java new file mode 100644 index 0000000..ad176f7 --- /dev/null +++ b/reverse-words-in-a-string-ii/Solution.java @@ -0,0 +1,30 @@ +public class Solution { + + void swap(char[] s, int i, int j){ + char t = s[i]; + s[i] = s[j]; + s[j] = t; + } + + void reverse(char[] s, int st, int ed){ + int l = ed - st; + + for(int i = st; i < st + l / 2; i++){ + swap(s, i, ed + st - i - 1); + } + } + + public void reverseWords(char[] s) { + reverse(s, 0, s.length); + + int nextWordStart = 0; + for(int i = 0; i < s.length; i++){ + if(s[i] == ' '){ + reverse(s, nextWordStart, i); + nextWordStart = i + 1; + } + } + + reverse(s, nextWordStart, s.length); + } +} diff --git a/reverse-words-in-a-string-ii/index.md b/reverse-words-in-a-string-ii/index.md new file mode 100644 index 0000000..55be95a --- /dev/null +++ b/reverse-words-in-a-string-ii/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Reverse Words in a String II +date: 2015-02-03 14:42:33 +0800 +leetcode_id: 186 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From cefe50f4d10002b07e11e2b08bec5d1843dd68ff Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 3 Feb 2015 14:44:49 +0800 Subject: [PATCH 079/195] up to date --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 960a627..1c3e913 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 960a6271b83c67612ff2a14d017e0778a9cd94bb +Subproject commit 1c3e913d946a8d53c76f4065299c5e2c12599fdf From f861b9ecd7b60a9af4b37a39f966c3976a1cdcd5 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Feb 2015 01:59:59 +0800 Subject: [PATCH 080/195] add repeated dns --- repeated-dna-sequences/README.md | 0 repeated-dna-sequences/Solution.java | 69 ++++++++++++++++++++++++++++ repeated-dna-sequences/index.md | 9 ++++ 3 files changed, 78 insertions(+) create mode 100644 repeated-dna-sequences/README.md create mode 100644 repeated-dna-sequences/Solution.java create mode 100644 repeated-dna-sequences/index.md diff --git a/repeated-dna-sequences/README.md b/repeated-dna-sequences/README.md new file mode 100644 index 0000000..e69de29 diff --git a/repeated-dna-sequences/Solution.java b/repeated-dna-sequences/Solution.java new file mode 100644 index 0000000..ce4deea --- /dev/null +++ b/repeated-dna-sequences/Solution.java @@ -0,0 +1,69 @@ +public class Solution { + + static final int SIZE = 10; + static final char[] CHAR_TO_INT = {'A', 'C', 'G', 'T'}; + static final int[] INT_TO_CHAR = new int['T' + 1]; + static final int[] POW = new int[SIZE]; + + static { + for(int i = 0; i < SIZE; i++){ + POW[i] = (int) Math.pow(4, i); + } + + INT_TO_CHAR['A'] = 0; + INT_TO_CHAR['C'] = 1; + INT_TO_CHAR['G'] = 2; + INT_TO_CHAR['T'] = 3; + } + + int toInt(char[] s, int index){ + if(index + 10 > s.length){ + return -1; + } + + int n = 0; + for(int i = index; i < index + 10; i++){ + n += INT_TO_CHAR[s[i]] * POW[i - index]; + } + + return n; + } + + String formInt(int n){ + + char[] s = new char[10]; + + for(int i = 0; i < 10; i++){ + int v = 4; + + s[i] = CHAR_TO_INT[n % v]; + + n /= v; + + } + return new String(s); + } + + + public List findRepeatedDnaSequences(String s) { + + char[] S = s.toCharArray(); + + final int max = toInt("TTTTTTTTTT".toCharArray(), 0); + int[] m = new int[max]; + + for(int i = 0; i <= S.length - 10; i++){ + m[toInt(S, i)]++; + } + + ArrayList rt = new ArrayList<>(); + + for(int i = 0; i < max; i++){ + if(m[i] >= 2){ + rt.add(formInt(i)); + } + } + + return rt; + } +} diff --git a/repeated-dna-sequences/index.md b/repeated-dna-sequences/index.md new file mode 100644 index 0000000..947845b --- /dev/null +++ b/repeated-dna-sequences/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Repeated DNA Sequences +date: 2015-02-07 01:58:50+08:00 +leetcode_id: 187 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 3cf6150b479ea8c72cb56273c9a5da02e941620a Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Feb 2015 02:00:33 +0800 Subject: [PATCH 081/195] up to date --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 1c3e913..f861b9e 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 1c3e913d946a8d53c76f4065299c5e2c12599fdf +Subproject commit f861b9ecd7b60a9af4b37a39f966c3976a1cdcd5 From b2929efd9dbecd53ee73995b23e76bc892c7efa1 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Feb 2015 02:08:09 +0800 Subject: [PATCH 082/195] fix some hardcode --- repeated-dna-sequences/Solution.java | 97 +++++++++++++--------------- 1 file changed, 46 insertions(+), 51 deletions(-) diff --git a/repeated-dna-sequences/Solution.java b/repeated-dna-sequences/Solution.java index ce4deea..6c01255 100644 --- a/repeated-dna-sequences/Solution.java +++ b/repeated-dna-sequences/Solution.java @@ -1,69 +1,64 @@ public class Solution { - - static final int SIZE = 10; - static final char[] CHAR_TO_INT = {'A', 'C', 'G', 'T'}; - static final int[] INT_TO_CHAR = new int['T' + 1]; - static final int[] POW = new int[SIZE]; - - static { - for(int i = 0; i < SIZE; i++){ - POW[i] = (int) Math.pow(4, i); + + static final int SIZE = 10; + static final char[] CHAR_TO_INT = {'A', 'C', 'G', 'T'}; + static final int[] INT_TO_CHAR = new int['T' + 1]; + static final int[] POW = new int[SIZE]; + + static { + for(int i = 0; i < SIZE; i++){ + POW[i] = (int) Math.pow(4, i); + } + + INT_TO_CHAR['A'] = 0; + INT_TO_CHAR['C'] = 1; + INT_TO_CHAR['G'] = 2; + INT_TO_CHAR['T'] = 3; } - INT_TO_CHAR['A'] = 0; - INT_TO_CHAR['C'] = 1; - INT_TO_CHAR['G'] = 2; - INT_TO_CHAR['T'] = 3; - } + int toInt(char[] s, int index){ + if(index + SIZE > s.length){ + return -1; + } - int toInt(char[] s, int index){ - if(index + 10 > s.length){ - return -1; - } + int n = 0; + for(int i = index; i < index + SIZE; i++){ + n += INT_TO_CHAR[s[i]] * POW[i - index]; + } - int n = 0; - for(int i = index; i < index + 10; i++){ - n += INT_TO_CHAR[s[i]] * POW[i - index]; + return n; } - return n; - } - - String formInt(int n){ - - char[] s = new char[10]; - - for(int i = 0; i < 10; i++){ - int v = 4; - - s[i] = CHAR_TO_INT[n % v]; - - n /= v; + String formInt(int n){ + char[] s = new char[SIZE]; + for(int i = 0; i < SIZE; i++){ + s[i] = CHAR_TO_INT[n % 4]; + n /= 4; + } + return new String(s); } - return new String(s); - } - public List findRepeatedDnaSequences(String s) { + public List findRepeatedDnaSequences(String s) { - char[] S = s.toCharArray(); + char[] S = s.toCharArray(); - final int max = toInt("TTTTTTTTTT".toCharArray(), 0); - int[] m = new int[max]; + final int max = toInt("TTTTTTTTTT".toCharArray(), 0); + int[] m = new int[max + 1]; - for(int i = 0; i <= S.length - 10; i++){ - m[toInt(S, i)]++; - } + for(int i = 0; i <= S.length - SIZE; i++){ + m[toInt(S, i)]++; + } - ArrayList rt = new ArrayList<>(); + ArrayList rt = new ArrayList<>(); - for(int i = 0; i < max; i++){ - if(m[i] >= 2){ - rt.add(formInt(i)); - } - } + for(int i = 0; i < max + 1; i++){ + if(m[i] >= 2){ + rt.add(formInt(i)); + } + } - return rt; - } + return rt; + } } From 6f4ff33a14b62f3e33b98e753de4acc1a329aaf7 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Feb 2015 02:28:55 +0800 Subject: [PATCH 083/195] update time --- _includes/_root | 2 +- repeated-dna-sequences/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/_includes/_root b/_includes/_root index f861b9e..b2929ef 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit f861b9ecd7b60a9af4b37a39f966c3976a1cdcd5 +Subproject commit b2929efd9dbecd53ee73995b23e76bc892c7efa1 diff --git a/repeated-dna-sequences/index.md b/repeated-dna-sequences/index.md index 947845b..f313a36 100644 --- a/repeated-dna-sequences/index.md +++ b/repeated-dna-sequences/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Repeated DNA Sequences -date: 2015-02-07 01:58:50+08:00 +date: 2015-02-07 02:08:09 +0800 leetcode_id: 187 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From fd36db47b004a8cc41873d62dbb247adb468e3f8 Mon Sep 17 00:00:00 2001 From: "Gao, Chao" Date: Thu, 12 Feb 2015 16:52:24 +0800 Subject: [PATCH 084/195] the var up is never used --- merge-sorted-array/Solution.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/merge-sorted-array/Solution.java b/merge-sorted-array/Solution.java index c937f40..91d78da 100644 --- a/merge-sorted-array/Solution.java +++ b/merge-sorted-array/Solution.java @@ -3,7 +3,7 @@ public void merge(int A[], int m, int B[], int n) { int pa = 0; int pb = 0; - int up = 0; + // int up = 0; while(pa < m + pb && pb < n){ @@ -30,4 +30,4 @@ public void merge(int A[], int m, int B[], int n) { } } -} \ No newline at end of file +} From 2f5a01d70f04683d8de62d0936aa381476cc5223 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 00:11:34 +0800 Subject: [PATCH 085/195] better code --- merge-sorted-array/Solution.java | 40 ++++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/merge-sorted-array/Solution.java b/merge-sorted-array/Solution.java index 91d78da..9dc079e 100644 --- a/merge-sorted-array/Solution.java +++ b/merge-sorted-array/Solution.java @@ -1,32 +1,32 @@ public class Solution { + + int safe(int X[], int i){ + if(i < 0) return Integer.MIN_VALUE; + + return X[i]; + } + public void merge(int A[], int m, int B[], int n) { - int pa = 0; - int pb = 0; - // int up = 0; + int t = A.length - 1; + + int pa = m - 1; + int pb = n - 1; - while(pa < m + pb && pb < n){ + while(t >= 0){ - int a = A[pa]; - int b = B[pb]; + int a = safe(A, pa); + int b = safe(B, pb); - if (a < b){ - pa++; + if(a > b){ + A[t] = a; + pa--; }else{ - // shift up - for(int i = pb + m; i > pa ; i--){ - A[i] = A[i - 1]; - } - - A[pa] = b; - pa++; - pb++; + A[t] = b; + pb--; } - } - - for( ; pb < n; pb++){ - A[pb + m] = B[pb]; + t--; } } From 85978d9a9488c246efccf5041304fd95a1351a54 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 00:34:52 +0800 Subject: [PATCH 086/195] Update README.md --- merge-sorted-array/README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/merge-sorted-array/README.md b/merge-sorted-array/README.md index f626951..5231993 100644 --- a/merge-sorted-array/README.md +++ b/merge-sorted-array/README.md @@ -15,9 +15,14 @@ Merge(left_sorted_part, right_sorted_part) ## Merging - 1. taking one (`l`) from `left_sorted_part` - 1. taking one (`r`) from `right_sorted_part` - 1. find the smaller(`s`) one in `l` and `r` - 1. put `s` into `result array` - 1. put bigger one back to `left_sorted_part` or `right_sorted_part` - 1. loop to step 1 until one is empty + 1. set `t` the end of `result array` + 1. taking one (`l`) from the end of `left_sorted_part` + 1. taking one (`r`) from the end of `right_sorted_part` + 1. find the larger(`g`) one in `l` and `r` + 1. put `g` at position `t` of `result array` + 1. loop until `t` reach the bottom of `result array` + +When `result array` is an empty array, +it is passable to copy from the beginning of `left_sorted_part` and `right_sorted_part`. + +In this problem, however, we have to copy from end to beginning due to that `left_sorted_part` and `result array` are sharing the same array. From 14ad29ce0b0c0db5e21e84ad8dc7d996726087e1 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 00:41:10 +0800 Subject: [PATCH 087/195] java 8 style --- gray-code/Solution.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/gray-code/Solution.java b/gray-code/Solution.java index f8f383d..ad1d369 100644 --- a/gray-code/Solution.java +++ b/gray-code/Solution.java @@ -1,15 +1,10 @@ public class Solution { - public ArrayList grayCode(int n) { + public List grayCode(int n) { - ArrayList rt = new ArrayList(); - - - for(int i = 0; i < Math.pow(2, n); i++){ - // G(N) = (B(n)/2) XOR B(n) - rt.add((i / 2) ^ i); - } - - return rt; + return IntStream.range(0, (int) Math.pow(2, n)) + .map(i -> (i >> 1) ^ i ) + .boxed() + .collect(Collectors.toList()); } -} \ No newline at end of file +} From 118c1ed7133279d8acd2f716389155d80471d947 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 00:44:38 +0800 Subject: [PATCH 088/195] Update README.md --- gray-code/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gray-code/README.md b/gray-code/README.md index 0e6338a..5f7f7b2 100644 --- a/gray-code/README.md +++ b/gray-code/README.md @@ -3,6 +3,7 @@ Shamelessly, I copied it from [Gray Code on Wikipedia](http://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code). ``` -G(N) = (B(n)/2) XOR B(n) +Gray(N) = (n >> 1) XOR n ``` +Tricky bit manipulation just change only 1 bit of `n` From 78764b6a7ad6b1100a379bb591da8b1e9456a4a0 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 01:10:10 +0800 Subject: [PATCH 089/195] java 8 style --- subsets/Solution.java | 39 ++++++++++----------------------------- 1 file changed, 10 insertions(+), 29 deletions(-) diff --git a/subsets/Solution.java b/subsets/Solution.java index f75027a..566f1d3 100644 --- a/subsets/Solution.java +++ b/subsets/Solution.java @@ -1,34 +1,15 @@ public class Solution { public List> subsets(int[] S) { - ArrayList> rt = new ArrayList>(); - - if (S.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - Arrays.sort(S); - - long mask = (long) Math.pow(2, S.length); - - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < S.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(S[(int)j]); - } - } - - rt.add(level); - - } - - return rt; + + return IntStream.range(0, 1 << S.length) + .mapToObj(mask -> + IntStream.range(0, S.length) + .filter(i -> ((1 << i) & mask) > 0) + .map(i -> S[i]) + .boxed() + .collect(Collectors.toList()) + ) + .collect(Collectors.toList()); } } From 0773f75ad4e943f2967cbc82f3f4f4f220736f51 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 01:14:40 +0800 Subject: [PATCH 090/195] java 8 style --- subsets-ii/Solution.java | 54 ++++++++-------------------------------- 1 file changed, 10 insertions(+), 44 deletions(-) diff --git a/subsets-ii/Solution.java b/subsets-ii/Solution.java index 676423c..49f039b 100644 --- a/subsets-ii/Solution.java +++ b/subsets-ii/Solution.java @@ -1,49 +1,15 @@ public class Solution { public List> subsetsWithDup(int[] num) { - - ArrayList> rt = new ArrayList>(); - - if (num.length == 0){ - rt.add(new ArrayList()); - - return rt; - } - Arrays.sort(num); - - long mask = (long) Math.pow(2, num.length); - - next: - for(long i = 0; i < mask; i++){ - - ArrayList level = new ArrayList(); - - for(long j = 0; j < num.length; j++){ - - long x = (long) Math.pow(2, j); - - if((x & i) == x){ - level.add(num[(int)j]); - } - } - - next_lv: - for(List _level : rt){ - - if(_level.size() == level.size()){ - for(int li = 0; li < _level.size(); li++){ - if(!_level.get(li).equals(level.get(li))) - continue next_lv; - } - - continue next; - } - } - rt.add(level); - - } - - return rt; - + + return new ArrayList<>(IntStream.range(0, 1 << num.length) + .mapToObj(mask -> + IntStream.range(0, num.length) + .filter(i -> ((1 << i) & mask) > 0) + .map(i -> num[i]) + .boxed() + .collect(Collectors.toList()) + ) + .collect(Collectors.toSet())); } } From 7cdd9fe385aae8ec855417cee8de601a42015989 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 01:18:49 +0800 Subject: [PATCH 091/195] update time --- gray-code/index.md | 2 +- merge-sorted-array/index.md | 2 +- subsets-ii/index.md | 2 +- subsets/index.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gray-code/index.md b/gray-code/index.md index 7a25493..25c0864 100644 --- a/gray-code/index.md +++ b/gray-code/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Gray Code -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-13 00:44:38 +0800 leetcode_id: 89 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/merge-sorted-array/index.md b/merge-sorted-array/index.md index adf43fc..c78f3e7 100644 --- a/merge-sorted-array/index.md +++ b/merge-sorted-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Merge Sorted Array -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-13 00:34:52 +0800 leetcode_id: 88 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/subsets-ii/index.md b/subsets-ii/index.md index 59c9588..a8e086a 100644 --- a/subsets-ii/index.md +++ b/subsets-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Subsets II -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-13 01:14:40 +0800 leetcode_id: 90 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/subsets/index.md b/subsets/index.md index 1cb378e..e7401c2 100644 --- a/subsets/index.md +++ b/subsets/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Subsets -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-13 01:10:10 +0800 leetcode_id: 78 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 127ee65cc25040579491bf7414487c65ac62e3c5 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 13 Feb 2015 01:21:54 +0800 Subject: [PATCH 092/195] sync gh-pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index b2929ef..7cdd9fe 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit b2929efd9dbecd53ee73995b23e76bc892c7efa1 +Subproject commit 7cdd9fe385aae8ec855417cee8de601a42015989 From d466bbc7d96d9fa1feed7086209bcc0e0eb18a47 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 16 Feb 2015 11:19:43 +0800 Subject: [PATCH 093/195] code clean up --- 3sum/Solution.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/3sum/Solution.java b/3sum/Solution.java index a158e28..912bfe0 100644 --- a/3sum/Solution.java +++ b/3sum/Solution.java @@ -3,16 +3,16 @@ public List> threeSum(int[] num) { Arrays.sort(num); - ArrayList> found = new ArrayList>(); + List> found = new ArrayList<>(); int pneg = 0 , ppos = num.length - 1; - while(ppos > 0 && num[ppos] >= 0){ - while(pneg < ppos && num[pneg] <= 0 && num[ppos] >= 0){ - int sum = num[pneg]; - sum += num[ppos]; + + while(pneg < ppos && num[pneg] <= 0){ + int sum = num[pneg] + num[ppos]; + for(int i = pneg + 1; i < ppos; i++){ if(num[i] + sum == 0){ found.add(Arrays.asList(new Integer[]{num[pneg], num[i] ,num[ppos]})); @@ -31,8 +31,6 @@ public List> threeSum(int[] num) { while(ppos > 0 && num[ppos] == old) ppos--; } - return found; - } } From f08672d1cc659afc78a1306742126e51981c23bf Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 16 Feb 2015 17:43:10 +0800 Subject: [PATCH 094/195] refine the code --- palindrome-number/Solution.java | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/palindrome-number/Solution.java b/palindrome-number/Solution.java index 8578bb7..aac49d6 100644 --- a/palindrome-number/Solution.java +++ b/palindrome-number/Solution.java @@ -1,26 +1,25 @@ public class Solution { + + int len(int x){ + return (int) Math.log10(x) + 1; + } + + int charAt(int x, int i){ + return (int) (x / Math.pow(10, i)) % 10; + } + public boolean isPalindrome(int x) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. - - - if(x < 0) return false; - - if(x == 0) return true; - - int size = (int)Math.log10(x); + if (x < 0 ) return false; + if (x == 0) return true; - int mid = size / 2; + int l = len(x); - for(int i = 0; i <= mid; i++){ - - int p = (int) (x / Math.pow(10, i)) % 10; - int q = (int) (x / Math.pow(10, size - i)) % 10; - if(p != q) + for(int i = 0; i < l / 2; i++){ + if(charAt(x, i) != charAt(x, l - i - 1)){ return false; - + } } return true; } -} \ No newline at end of file +} From 4d57bc95e5ce9ee5f9fc997650f9e3be87a5d566 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 4 Mar 2015 01:39:57 +0800 Subject: [PATCH 095/195] add new easy one --- rotate-array/README.md | 0 rotate-array/Solution.java | 33 +++++++++++++++++++++++++++++++++ rotate-array/index.md | 9 +++++++++ 3 files changed, 42 insertions(+) create mode 100644 rotate-array/README.md create mode 100644 rotate-array/Solution.java create mode 100644 rotate-array/index.md diff --git a/rotate-array/README.md b/rotate-array/README.md new file mode 100644 index 0000000..e69de29 diff --git a/rotate-array/Solution.java b/rotate-array/Solution.java new file mode 100644 index 0000000..101b714 --- /dev/null +++ b/rotate-array/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + public void rotate(int[] nums, int k) { + + if(k == 0) return; + + + int c = 0; + + for(int j = 0; j < k; j++) { + int i = j; + int t = nums[i]; + + + for (;;) { + + i = (i + k) % nums.length; + + int nt = nums[i]; + + nums[i] = t; + + t = nt; + + c++; + + if (i == j) break; + } + + if(c == nums.length) break; + } + + } +} diff --git a/rotate-array/index.md b/rotate-array/index.md new file mode 100644 index 0000000..59d0c50 --- /dev/null +++ b/rotate-array/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Rotate Array +date: 2015-03-04 01:37:50+08:00 +leetcode_id: 189 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 88a350bf4f8288ecda90123f22ab0b3576d8859d Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 4 Mar 2015 01:43:30 +0800 Subject: [PATCH 096/195] new pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 7cdd9fe..4d57bc9 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 7cdd9fe385aae8ec855417cee8de601a42015989 +Subproject commit 4d57bc95e5ce9ee5f9fc997650f9e3be87a5d566 From bbbc717a62045ca21c6d7518e537831e4907bcac Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 4 Mar 2015 19:20:53 +0800 Subject: [PATCH 097/195] fuck tle shameless cheat ver --- best-time-to-buy-and-sell-stock-iv/README.md | 0 .../Solution.java | 66 +++++++++++++++++++ best-time-to-buy-and-sell-stock-iv/index.md | 9 +++ 3 files changed, 75 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock-iv/README.md create mode 100644 best-time-to-buy-and-sell-stock-iv/Solution.java create mode 100644 best-time-to-buy-and-sell-stock-iv/index.md diff --git a/best-time-to-buy-and-sell-stock-iv/README.md b/best-time-to-buy-and-sell-stock-iv/README.md new file mode 100644 index 0000000..e69de29 diff --git a/best-time-to-buy-and-sell-stock-iv/Solution.java b/best-time-to-buy-and-sell-stock-iv/Solution.java new file mode 100644 index 0000000..34c54fa --- /dev/null +++ b/best-time-to-buy-and-sell-stock-iv/Solution.java @@ -0,0 +1,66 @@ +public class Solution { + public int maxProfit(int k, int[] prices) { + k = Math.min(k, prices.length); + if(k <= 0) return 0; + + // shit cheat + if(k >= prices.length) return maxProfit(prices); + + int[][] P = new int[k + 1][prices.length]; + int[][] H = new int[k + 1][prices.length]; + + int[] D = new int[prices.length]; + + for(int i = 1; i < prices.length; i++){ + D[i] = prices[i] - prices[i - 1]; + } + + int si = 1; + + for(int j = 1; j <= k; j++) { + + for (int i = si; i < prices.length; i++) { + + H[j][i] = Math.max(H[j][i - 1] + D[i], P[j - 1][i - 1]); + + P[j][i] = Math.max(H[j][i], P[j][i - 1]); + + } + + for (int i = si + 1; i < prices.length; i++) { + if(P[j - 1][i] == P[j][i]) { + si = i; + } + } + + if(si == prices.length - 1){ + return P[j][prices.length - 1]; + } + } + + return P[k][prices.length - 1]; + } + + // best-time-to-buy-and-sell-stock-ii + int maxProfit(int[] prices) { + + if(prices.length <= 1) return 0; + + int profit = 0; + + int hold = prices[0]; + + for(int i = 1; i < prices.length; i++){ + + + if(hold < prices[i]){ + profit += prices[i] - hold; // sell + + } + + hold = prices[i]; + } + + return profit; + } +} diff --git a/best-time-to-buy-and-sell-stock-iv/index.md b/best-time-to-buy-and-sell-stock-iv/index.md new file mode 100644 index 0000000..47cb251 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-iv/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Best Time to Buy and Sell Stock IV +date: 2015-03-04 19:18:34+08:00 +leetcode_id: 188 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 974950ac7207033eddf638dc03616199f6f4b250 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 4 Mar 2015 19:21:31 +0800 Subject: [PATCH 098/195] add buy sell stock iv --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 4d57bc9..bbbc717 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 4d57bc95e5ce9ee5f9fc997650f9e3be87a5d566 +Subproject commit bbbc717a62045ca21c6d7518e537831e4907bcac From 9807b1a4d4acba31d011063c46f823481375c03c Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Mar 2015 19:36:21 +0800 Subject: [PATCH 099/195] add reverse bits --- reverse-bits/README.md | 0 reverse-bits/Solution.java | 29 +++++++++++++++++++++++++++++ reverse-bits/index.md | 9 +++++++++ 3 files changed, 38 insertions(+) create mode 100644 reverse-bits/README.md create mode 100644 reverse-bits/Solution.java create mode 100644 reverse-bits/index.md diff --git a/reverse-bits/README.md b/reverse-bits/README.md new file mode 100644 index 0000000..e69de29 diff --git a/reverse-bits/Solution.java b/reverse-bits/Solution.java new file mode 100644 index 0000000..c2dd4bb --- /dev/null +++ b/reverse-bits/Solution.java @@ -0,0 +1,29 @@ +public class Solution { + + // from JDK Integer.reverse + + /** + * Returns the value obtained by reversing the order of the bits in the + * two's complement binary representation of the specified {@code int} + * value. + * + * @param i the value to be reversed + * @return the value obtained by reversing order of the bits in the + * specified {@code int} value. + * @since 1.5 + */ + public static int reverse(int i) { + // HD, Figure 7-1 + i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; + i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; + i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; + i = (i << 24) | ((i & 0xff00) << 8) | + ((i >>> 8) & 0xff00) | (i >>> 24); + return i; + } + + // you need treat n as an unsigned value + public int reverseBits(int n) { + return reverse(n); + } +} diff --git a/reverse-bits/index.md b/reverse-bits/index.md new file mode 100644 index 0000000..83e5573 --- /dev/null +++ b/reverse-bits/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Reverse Bits +date: 2015-03-07 19:33:34+08:00 +leetcode_id: 190 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From ad1a49fd1cc6097c22a37c8c0280bbeb1945b473 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 7 Mar 2015 19:37:12 +0800 Subject: [PATCH 100/195] update pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index bbbc717..9807b1a 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit bbbc717a62045ca21c6d7518e537831e4907bcac +Subproject commit 9807b1a4d4acba31d011063c46f823481375c03c From b5a75cb0ff30d3e6c07412ea2a0d86e67f0891c8 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 8 Mar 2015 01:04:43 +0800 Subject: [PATCH 101/195] add best time to buy and sell iv --- best-time-to-buy-and-sell-stock-iv/README.md | 143 +++++++++++++++++++ 1 file changed, 143 insertions(+) diff --git a/best-time-to-buy-and-sell-stock-iv/README.md b/best-time-to-buy-and-sell-stock-iv/README.md index e69de29..de99856 100644 --- a/best-time-to-buy-and-sell-stock-iv/README.md +++ b/best-time-to-buy-and-sell-stock-iv/README.md @@ -0,0 +1,143 @@ +## [Best Time to Buy and Sell Stock](../best-time-to-buy-and-sell-stock) k times like [Best Time to Buy and Sell Stock III](../best-time-to-buy-and-sell-stock-iii) + + _Note: This is a TLE version. `O(n^3)`. but, easier to understand_ + + ``` + | + | * * + * | * * * + * * | * * +* * |* * + * | * * * + * *| * * + | * + | + i +``` + +`day i` separates days into `0..i` and `i..end`. +just assume that you know max profit `k - 1` times for `0..i` day is `maxProfit(k - 1, 0..i)`. + +such that + +the max profit of buy and sell only once after `day i` is `maxProfit(k - 1, 0..i) + maxProfit(1, i..end)`. +just do as [Best Time to Buy and Sell Stock III](../best-time-to-buy-and-sell-stock-iii), +brute force `i` to find the max profit. + +``` +maxProfit(k, m..n) = { + + if k == 1 then + return call maxProfit1(m..n) // best buy and sell once + else + return + MAX { + for i = 0 .. end + maxProfit(k - 1, m..i) + maxProfit(1, i..n) + } +} + +``` + +when `k = 2` + +the func becomes [Best Time to Buy and Sell Stock III](../best-time-to-buy-and-sell-stock-iii) + +``` + return MAX { + for i = 0 .. end + maxProfit1(m..i) + maxProfit1(i..n) // m..i is left part and i..n is right part + } +``` + +## [Maximum Subarray](../maximum-subarray) like version + +I dont like this because I dont think it is easy to understand. +However, this will reduce the time complexity from `O(n^3)` to `O(n^2)`. + +### Start from [Best Time to Buy and Sell Stock](../best-time-to-buy-and-sell-stock) + +In the [Maximum Subarray](../maximum-subarray), +numbers are always added to the variable `history`. +when the `history` goes below zero, just drop it. + +This is like you and a fool buy and sell stock together, +the fool buys and sells his stocks everyday. +Whenever the fool earns more money than you at `day i`, +you could act like fool to get to max profit from `day 0` to `day i`. +otherwise, just keep the max profit. +Sometimes, the fool may go broke, just change another fool. + + +Talk is cheap, show you the code + +``` +public int maxProfit(int[] prices) { + + if(prices.length < 1) return 0; + + int[] P = new int[prices.length]; // this is you + int[] H = new int[prices.length]; // this is that fool + // H is short for history like Maximum Subarray + + for(int i = 1; i < prices.length; i++){ + int p = prices[i] - prices[i - 1]; + + H[i] = Math.max(H[i - 1] + p, 0); // buy and sell + // max(H, 0) means when fool goes broke, just start from another + + P[i] = Math.max(H[i], P[i - 1]); // if the fool earns more than you + // time to act like the fool to get max profit + } + + return P[prices.length - 1]; +} + +``` + +### Extends to K times + +just exntends P and H to 2d. `P[time][day]` + + +the only difference is change + +``` +H[j][i] = Math.max(H[j][i - 1] + p, 0); +``` + +to + +``` +H[j][i] = Math.max(H[j][i - 1] + p, P[j - 1][i - 1]); +``` + +that means the fool should act better than buy and sell `k - 1` times until `day i - 1` (`P[k - 1][i - 1]`), +or the fool should restart from `P[k - 1][i - 1]` in order to get better profit. + +``` +int[][] P = new int[k + 1][prices.length]; +int[][] H = new int[k + 1][prices.length]; + +for(int j = 1; j <= k; j++) { + + for (int i = 1; i < prices.length; i++) { + int p = prices[i] - prices[i - 1]; + + H[j][i] = Math.max(H[j][i - 1] + p, P[j - 1][i - 1]); + + P[j][i] = Math.max(H[j][i], P[j][i - 1]); + } +} +``` + +## Final cheat + +I did some optimization to avoid TLE, +like caching the difference of `price i` and `price i - 1` into `D`. +but leetcode still reject my code. + +I found some test cases is really big, +but can be got `O(n)` using [Best Time to Buy and Sell Stock II](../best-time-to-buy-and-sell-stock-ii) +because `k > len(prices)`. + From b23ab13d1904d3a0daa376317fd900de5e0e54ae Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 8 Mar 2015 01:16:06 +0800 Subject: [PATCH 102/195] add dna seq --- repeated-dna-sequences/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/repeated-dna-sequences/README.md b/repeated-dna-sequences/README.md index e69de29..a701e88 100644 --- a/repeated-dna-sequences/README.md +++ b/repeated-dna-sequences/README.md @@ -0,0 +1,6 @@ +## [Quaternary](http://en.wikipedia.org/wiki/Quaternary_numeral_system#Genetics) + +This is just a smarter brute force. +10 char of (A C G T) can only represent `4 ^ 10` combinations. + +Covert `ACGT` into numbers and count them using a `int[4 ^ 10]`. From 9c18221527faa346ea8edf922d8671a5e7539251 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 8 Mar 2015 01:18:23 +0800 Subject: [PATCH 103/195] update time --- 3sum/index.md | 2 +- best-time-to-buy-and-sell-stock-iv/index.md | 2 +- palindrome-number/index.md | 2 +- repeated-dna-sequences/index.md | 2 +- reverse-bits/index.md | 2 +- rotate-array/index.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/3sum/index.md b/3sum/index.md index 16827d0..672d40d 100644 --- a/3sum/index.md +++ b/3sum/index.md @@ -1,7 +1,7 @@ --- layout: solution title: 3Sum -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-16 11:19:43 +0800 leetcode_id: 15 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/best-time-to-buy-and-sell-stock-iv/index.md b/best-time-to-buy-and-sell-stock-iv/index.md index 47cb251..4e1ba22 100644 --- a/best-time-to-buy-and-sell-stock-iv/index.md +++ b/best-time-to-buy-and-sell-stock-iv/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Best Time to Buy and Sell Stock IV -date: 2015-03-04 19:18:34+08:00 +date: 2015-03-08 01:04:43 +0800 leetcode_id: 188 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/palindrome-number/index.md b/palindrome-number/index.md index 4f0cb66..b86af95 100644 --- a/palindrome-number/index.md +++ b/palindrome-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Palindrome Number -date: 2014-12-29 00:26:24 +0800 +date: 2015-02-16 17:43:10 +0800 leetcode_id: 9 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/repeated-dna-sequences/index.md b/repeated-dna-sequences/index.md index f313a36..dc814f3 100644 --- a/repeated-dna-sequences/index.md +++ b/repeated-dna-sequences/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Repeated DNA Sequences -date: 2015-02-07 02:08:09 +0800 +date: 2015-03-08 01:16:06 +0800 leetcode_id: 187 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/reverse-bits/index.md b/reverse-bits/index.md index 83e5573..e5ef1de 100644 --- a/reverse-bits/index.md +++ b/reverse-bits/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Bits -date: 2015-03-07 19:33:34+08:00 +date: 2015-03-07 19:36:21 +0800 leetcode_id: 190 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/rotate-array/index.md b/rotate-array/index.md index 59d0c50..fd5a686 100644 --- a/rotate-array/index.md +++ b/rotate-array/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Rotate Array -date: 2015-03-04 01:37:50+08:00 +date: 2015-03-04 01:39:57 +0800 leetcode_id: 189 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 2b1c3d2bae3ac3fafdece41965705ab469f5255f Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 8 Mar 2015 01:19:11 +0800 Subject: [PATCH 104/195] new docs --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 9807b1a..9c18221 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 9807b1a4d4acba31d011063c46f823481375c03c +Subproject commit 9c18221527faa346ea8edf922d8671a5e7539251 From bb909aa57f2ffd900c12949a2f59fa81423c0e7f Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 10 Mar 2015 12:33:10 +0800 Subject: [PATCH 105/195] new 1 bit copy from jdk --- number-of-1-bits/README.md | 0 number-of-1-bits/Solution.java | 27 +++++++++++++++++++++++++++ number-of-1-bits/index.md | 9 +++++++++ 3 files changed, 36 insertions(+) create mode 100644 number-of-1-bits/README.md create mode 100644 number-of-1-bits/Solution.java create mode 100644 number-of-1-bits/index.md diff --git a/number-of-1-bits/README.md b/number-of-1-bits/README.md new file mode 100644 index 0000000..e69de29 diff --git a/number-of-1-bits/Solution.java b/number-of-1-bits/Solution.java new file mode 100644 index 0000000..d1f23e7 --- /dev/null +++ b/number-of-1-bits/Solution.java @@ -0,0 +1,27 @@ +public class Solution { + // copy from JDK Integer.bitCount + /** + * Returns the number of one-bits in the two's complement binary + * representation of the specified {@code int} value. This function is + * sometimes referred to as the population count. + * + * @param i the value whose bits are to be counted + * @return the number of one-bits in the two's complement binary + * representation of the specified {@code int} value. + * @since 1.5 + */ + public static int bitCount(int i) { + // HD, Figure 5-2 + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; + } + + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + return bitCount(n); + } +} diff --git a/number-of-1-bits/index.md b/number-of-1-bits/index.md new file mode 100644 index 0000000..f793a9b --- /dev/null +++ b/number-of-1-bits/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Number of 1 Bits +date: 2015-03-10 12:29:58+08:00 +leetcode_id: 191 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 5f84782516d577fcb37659218fdacab6ba4a860c Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 10 Mar 2015 12:33:41 +0800 Subject: [PATCH 106/195] update doc --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 9c18221..bb909aa 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 9c18221527faa346ea8edf922d8671a5e7539251 +Subproject commit bb909aa57f2ffd900c12949a2f59fa81423c0e7f From 2b5643cce4dca35fc74bf85af23eec13775488ea Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 20 Mar 2015 12:51:52 +0800 Subject: [PATCH 107/195] remove unused code --- triangle/Solution.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/triangle/Solution.java b/triangle/Solution.java index f9d3d4d..6962e7e 100644 --- a/triangle/Solution.java +++ b/triangle/Solution.java @@ -1,6 +1,6 @@ public class Solution { public int minimumTotal(List> triangle) { - + final int size = triangle.size(); if(size == 0) return 0; if(size == 1) return triangle.get(0).get(0); @@ -8,7 +8,9 @@ public int minimumTotal(List> triangle) { int[] s = new int[size]; int i = 0; - for(int v : triangle.get(size - 1)) s[i++] = v; + for(int v : triangle.get(size - 1)){ + s[i++] = v; + } for(i = size - 2; i >=0 ; i--){ List step = triangle.get(i); @@ -19,7 +21,6 @@ public int minimumTotal(List> triangle) { s[j] = Math.min(step.get(j) + s[j], step.get(j) + s[j + 1]); } - s[step.size()] = Integer.MAX_VALUE; } return s[0]; From 6fbc7c4d6ec98b05a609fae18af72b1e320b40ea Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 31 Mar 2015 15:38:38 +0800 Subject: [PATCH 108/195] add house robber --- house-robber/README.md | 0 house-robber/Solution.java | 17 +++++++++++++++++ house-robber/index.md | 9 +++++++++ 3 files changed, 26 insertions(+) create mode 100644 house-robber/README.md create mode 100644 house-robber/Solution.java create mode 100644 house-robber/index.md diff --git a/house-robber/README.md b/house-robber/README.md new file mode 100644 index 0000000..e69de29 diff --git a/house-robber/Solution.java b/house-robber/Solution.java new file mode 100644 index 0000000..aa44ea0 --- /dev/null +++ b/house-robber/Solution.java @@ -0,0 +1,17 @@ +public class Solution { + public int rob(int[] num) { + if(num.length == 0) return 0; + if(num.length == 1) return num[0]; + + int[] P = new int[Math.max(num.length, 2)]; + + P[0] = num[0]; + P[1] = Math.max(num[0], num[1]); + + for(int i = 2; i < num.length; i++){ + P[i] = Math.max(num[i] + P[i - 2], P[i - 1]); + } + + return P[num.length - 1]; + } +} diff --git a/house-robber/index.md b/house-robber/index.md new file mode 100644 index 0000000..a0a8dae --- /dev/null +++ b/house-robber/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: House Robber +date: 2015-03-31 15:37:17+08:00 +leetcode_id: 198 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 79b9307a7cb02467b07ae13ce16ac4e32ec571e8 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 31 Mar 2015 15:39:13 +0800 Subject: [PATCH 109/195] sync latest pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index bb909aa..6fbc7c4 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit bb909aa57f2ffd900c12949a2f59fa81423c0e7f +Subproject commit 6fbc7c4d6ec98b05a609fae18af72b1e320b40ea From 05bc79ed51fcba906011f1cade9e927adf1e68b8 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 31 Mar 2015 15:41:20 +0800 Subject: [PATCH 110/195] remove unused code --- house-robber/Solution.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/house-robber/Solution.java b/house-robber/Solution.java index aa44ea0..1c4f5a0 100644 --- a/house-robber/Solution.java +++ b/house-robber/Solution.java @@ -2,16 +2,16 @@ public class Solution { public int rob(int[] num) { if(num.length == 0) return 0; if(num.length == 1) return num[0]; - - int[] P = new int[Math.max(num.length, 2)]; - + + int[] P = new int[num.length]; + P[0] = num[0]; P[1] = Math.max(num[0], num[1]); for(int i = 2; i < num.length; i++){ P[i] = Math.max(num[i] + P[i - 2], P[i - 1]); } - + return P[num.length - 1]; } } From 9bcbf36a7d80c66f0e58d7fce24dd4ec6853c8fb Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 31 Mar 2015 20:10:39 +0800 Subject: [PATCH 111/195] add rob doc --- house-robber/README.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/house-robber/README.md b/house-robber/README.md index e69de29..2ebe8c4 100644 --- a/house-robber/README.md +++ b/house-robber/README.md @@ -0,0 +1,33 @@ +## Rob or not + +assume that there are 9 houses along the street +and you have a `rob` func can tell you the how much money you can get from first 8 hourses. + + +what about the 9th house + +``` +? = not sure +* = must rob +_ = must not rob + +rob + +[? ? ? ? ? ? ? ?] _ * +[0 1 2 3 4 5 6 7] 8 9 + +money = rob(0..7) + house_value[9] + +or not + +[? ? ? ? ? ? ? ? ?] _ +[0 1 2 3 4 5 6 7 8] 9 + +money = rob(0..8) + + +rob(0..9) = max(rob(0..8), rob(0..7) + house_value[9]) +``` + +then it is easy to write a `rob(0..n)` + From 2ccdb80b6476ae4a7194fc5cfc18d8b6fe62115b Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 3 Apr 2015 21:32:41 +0800 Subject: [PATCH 112/195] add binary tree right view --- binary-tree-right-side-view/README.md | 0 binary-tree-right-side-view/Solution.java | 34 +++++++++++++++++++++++ binary-tree-right-side-view/index.md | 9 ++++++ 3 files changed, 43 insertions(+) create mode 100644 binary-tree-right-side-view/README.md create mode 100644 binary-tree-right-side-view/Solution.java create mode 100644 binary-tree-right-side-view/index.md diff --git a/binary-tree-right-side-view/README.md b/binary-tree-right-side-view/README.md new file mode 100644 index 0000000..e69de29 diff --git a/binary-tree-right-side-view/Solution.java b/binary-tree-right-side-view/Solution.java new file mode 100644 index 0000000..f3722ae --- /dev/null +++ b/binary-tree-right-side-view/Solution.java @@ -0,0 +1,34 @@ +/** + * Definition for binary tree + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + static final TreeNode SEP = new TreeNode(0); + + public List rightSideView(TreeNode root) { + + if(root == null) return new ArrayList<>(); + + List rt = new ArrayList<>(); + + rt.add(root.val); + + List left = rightSideView(root.left); + List right = rightSideView(root.right); + + rt.addAll(right); + + if(left.size() > right.size()){ + rt.addAll(left.subList(right.size(), left.size())); + } + + + return rt; + } +} diff --git a/binary-tree-right-side-view/index.md b/binary-tree-right-side-view/index.md new file mode 100644 index 0000000..d21fb97 --- /dev/null +++ b/binary-tree-right-side-view/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Binary Tree Right Side View +date: 2015-04-03 21:31:10+08:00 +leetcode_id: 199 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 4f86c12ebe5a9893356c774b8cccdb339e949f93 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 3 Apr 2015 21:33:16 +0800 Subject: [PATCH 113/195] update time --- binary-tree-right-side-view/index.md | 2 +- house-robber/index.md | 2 +- number-of-1-bits/index.md | 2 +- triangle/index.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/binary-tree-right-side-view/index.md b/binary-tree-right-side-view/index.md index d21fb97..3d08d66 100644 --- a/binary-tree-right-side-view/index.md +++ b/binary-tree-right-side-view/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Right Side View -date: 2015-04-03 21:31:10+08:00 +date: 2015-04-03 21:32:41 +0800 leetcode_id: 199 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/house-robber/index.md b/house-robber/index.md index a0a8dae..80859c3 100644 --- a/house-robber/index.md +++ b/house-robber/index.md @@ -1,7 +1,7 @@ --- layout: solution title: House Robber -date: 2015-03-31 15:37:17+08:00 +date: 2015-03-31 20:10:39 +0800 leetcode_id: 198 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/number-of-1-bits/index.md b/number-of-1-bits/index.md index f793a9b..ea4fbeb 100644 --- a/number-of-1-bits/index.md +++ b/number-of-1-bits/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Number of 1 Bits -date: 2015-03-10 12:29:58+08:00 +date: 2015-03-10 12:33:10 +0800 leetcode_id: 191 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} diff --git a/triangle/index.md b/triangle/index.md index 9a46f07..15935f4 100644 --- a/triangle/index.md +++ b/triangle/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Triangle -date: 2014-12-29 00:26:24 +0800 +date: 2015-03-20 12:51:52 +0800 leetcode_id: 120 --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} From 7ec957224d0d94a335d724411ddc50298d1ddda2 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 3 Apr 2015 21:33:50 +0800 Subject: [PATCH 114/195] update gh-pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 6fbc7c4..4f86c12 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 6fbc7c4d6ec98b05a609fae18af72b1e320b40ea +Subproject commit 4f86c12ebe5a9893356c774b8cccdb339e949f93 From 5288343aefc316b99043a4e93107b53960c3fb2c Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 3 Apr 2015 21:37:44 +0800 Subject: [PATCH 115/195] remove code left in bfs --- binary-tree-right-side-view/Solution.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/binary-tree-right-side-view/Solution.java b/binary-tree-right-side-view/Solution.java index f3722ae..472d280 100644 --- a/binary-tree-right-side-view/Solution.java +++ b/binary-tree-right-side-view/Solution.java @@ -8,9 +8,6 @@ * } */ public class Solution { - - static final TreeNode SEP = new TreeNode(0); - public List rightSideView(TreeNode root) { if(root == null) return new ArrayList<>(); From 8bed653257d39f3fe6c829105ad8b362854523ee Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 3 Apr 2015 21:38:43 +0800 Subject: [PATCH 116/195] update gh-pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 4f86c12..5288343 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 4f86c12ebe5a9893356c774b8cccdb339e949f93 +Subproject commit 5288343aefc316b99043a4e93107b53960c3fb2c From ea68d4f9bea0987ab941317d254d2ee9addf38d2 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 13:29:32 +0800 Subject: [PATCH 117/195] add number of islands --- number-of-islands/README.md | 0 number-of-islands/Solution.java | 53 +++++++++++++++++++++++++++++++++ number-of-islands/index.md | 9 ++++++ 3 files changed, 62 insertions(+) create mode 100644 number-of-islands/README.md create mode 100644 number-of-islands/Solution.java create mode 100644 number-of-islands/index.md diff --git a/number-of-islands/README.md b/number-of-islands/README.md new file mode 100644 index 0000000..e69de29 diff --git a/number-of-islands/Solution.java b/number-of-islands/Solution.java new file mode 100644 index 0000000..a772d48 --- /dev/null +++ b/number-of-islands/Solution.java @@ -0,0 +1,53 @@ +public class Solution { + + boolean allowed(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){ + return (x < mx) && (x >= 0) + && (y < my) && (y >= 0) + && (grid[x][y] == '1') + && (!visited[x][y]); + } + + void travel(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited){ + + // x - 1, y + // x + 1, y + // x, y - 1 + // x, y + 1 + + visited[x][y] = true; + + for(int[] xy: new int[][]{{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}}){ + + int _x = xy[0]; + int _y = xy[1]; + + if(allowed(_x, _y, mx, my, grid, visited)){ + travel(_x, _y, mx, my, grid, visited); + } + } + + } + + public int numIslands(char[][] grid) { + + final int mx = grid.length; + if(mx == 0) return 0; + final int my = grid[0].length; + + int count = 0; + boolean[][] visited = new boolean[mx][my]; + + for(int x = 0; x < mx; x++){ + for(int y = 0; y < my; y++){ + if(allowed(x, y, mx, my, grid, visited)){ + + travel(x, y, mx, my, grid, visited); + + count++; + } + } + } + + return count; + } +} diff --git a/number-of-islands/index.md b/number-of-islands/index.md new file mode 100644 index 0000000..75835c5 --- /dev/null +++ b/number-of-islands/index.md @@ -0,0 +1,9 @@ +--- +layout: solution +title: Number of Islands +date: 2015-04-08 13:28:15+08:00 +leetcode_id: 200 +--- +{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} +{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} +{% include {{leetcode_readme}} %} From 398daafe38ce1b6835ac1cdecf3bc35cf27b3889 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 13:30:02 +0800 Subject: [PATCH 118/195] update gh-pages --- _includes/_root | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/_root b/_includes/_root index 5288343..ea68d4f 160000 --- a/_includes/_root +++ b/_includes/_root @@ -1 +1 @@ -Subproject commit 5288343aefc316b99043a4e93107b53960c3fb2c +Subproject commit ea68d4f9bea0987ab941317d254d2ee9addf38d2 From 2013b6fa5e628a95cbbb02a7328a42fd50195cb0 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 15:07:14 +0800 Subject: [PATCH 119/195] move to include_relative --- .gitmodules | 4 ---- 3sum-closest/index.md | 4 +--- 3sum/index.md | 4 +--- 4sum/index.md | 4 +--- _includes/_root | 1 - _layouts/solution.html | 3 +-- add-binary/index.md | 4 +--- add-two-numbers/index.md | 4 +--- anagrams/index.md | 4 +--- balanced-binary-tree/index.md | 4 +--- best-time-to-buy-and-sell-stock-ii/index.md | 4 +--- best-time-to-buy-and-sell-stock-iii/index.md | 4 +--- best-time-to-buy-and-sell-stock-iv/index.md | 4 +--- best-time-to-buy-and-sell-stock/index.md | 4 +--- binary-search-tree-iterator/index.md | 4 +--- binary-tree-inorder-traversal/index.md | 4 +--- binary-tree-level-order-traversal-ii/index.md | 4 +--- binary-tree-level-order-traversal/index.md | 4 +--- binary-tree-maximum-path-sum/index.md | 4 +--- binary-tree-postorder-traversal/index.md | 4 +--- binary-tree-preorder-traversal/index.md | 4 +--- binary-tree-right-side-view/index.md | 4 +--- binary-tree-upside-down/index.md | 4 +--- binary-tree-zigzag-level-order-traversal/index.md | 4 +--- candy/index.md | 4 +--- climbing-stairs/index.md | 4 +--- clone-graph/index.md | 4 +--- combination-sum-ii/index.md | 4 +--- combination-sum/index.md | 4 +--- combinations/index.md | 4 +--- compare-version-numbers/index.md | 4 +--- .../index.md | 4 +--- .../index.md | 4 +--- container-with-most-water/index.md | 4 +--- convert-sorted-array-to-binary-search-tree/index.md | 4 +--- convert-sorted-list-to-binary-search-tree/index.md | 4 +--- copy-list-with-random-pointer/index.md | 4 +--- count-and-say/index.md | 4 +--- decode-ways/index.md | 4 +--- distinct-subsequences/index.md | 4 +--- divide-two-integers/index.md | 4 +--- dungeon-game/index.md | 4 +--- edit-distance/index.md | 4 +--- evaluate-reverse-polish-notation/index.md | 4 +--- excel-sheet-column-number/index.md | 4 +--- excel-sheet-column-title/index.md | 4 +--- factorial-trailing-zeroes/index.md | 4 +--- find-minimum-in-rotated-sorted-array-ii/index.md | 4 +--- find-minimum-in-rotated-sorted-array/index.md | 4 +--- find-peak-element/index.md | 4 +--- first-missing-positive/index.md | 4 +--- flatten-binary-tree-to-linked-list/index.md | 4 +--- fraction-to-recurring-decimal/index.md | 4 +--- gas-station/index.md | 4 +--- generate-parentheses/index.md | 4 +--- gray-code/index.md | 4 +--- house-robber/index.md | 4 +--- implement-strstr/index.md | 4 +--- insert-interval/index.md | 4 +--- insertion-sort-list/index.md | 4 +--- integer-to-roman/index.md | 4 +--- interleaving-string/index.md | 4 +--- intersection-of-two-linked-lists/index.md | 4 +--- jump-game-ii/index.md | 4 +--- jump-game/index.md | 4 +--- largest-number/index.md | 4 +--- largest-rectangle-in-histogram/index.md | 4 +--- length-of-last-word/index.md | 4 +--- letter-combinations-of-a-phone-number/index.md | 4 +--- linked-list-cycle-ii/index.md | 4 +--- linked-list-cycle/index.md | 4 +--- longest-common-prefix/index.md | 4 +--- longest-consecutive-sequence/index.md | 4 +--- longest-palindromic-substring/index.md | 4 +--- .../index.md | 4 +--- longest-substring-without-repeating-characters/index.md | 4 +--- longest-valid-parentheses/index.md | 4 +--- lru-cache/index.md | 4 +--- majority-element/index.md | 4 +--- max-points-on-a-line/index.md | 4 +--- maximal-rectangle/index.md | 4 +--- maximum-depth-of-binary-tree/index.md | 4 +--- maximum-gap/index.md | 4 +--- maximum-product-subarray/index.md | 4 +--- maximum-subarray/index.md | 4 +--- median-of-two-sorted-arrays/index.md | 4 +--- merge-intervals/index.md | 4 +--- merge-k-sorted-lists/index.md | 4 +--- merge-sorted-array/index.md | 4 +--- merge-two-sorted-lists/index.md | 4 +--- min-stack/index.md | 4 +--- minimum-depth-of-binary-tree/index.md | 4 +--- minimum-path-sum/index.md | 4 +--- minimum-window-substring/index.md | 4 +--- missing-ranges/index.md | 4 +--- multiply-strings/index.md | 4 +--- n-queens-ii/index.md | 4 +--- n-queens/index.md | 4 +--- next-permutation/index.md | 4 +--- number-of-1-bits/index.md | 4 +--- number-of-islands/index.md | 4 +--- one-edit-distance/index.md | 4 +--- palindrome-number/index.md | 4 +--- palindrome-partitioning-ii/index.md | 4 +--- palindrome-partitioning/index.md | 4 +--- partition-list/index.md | 4 +--- pascals-triangle-ii/index.md | 4 +--- pascals-triangle/index.md | 4 +--- path-sum-ii/index.md | 4 +--- path-sum/index.md | 4 +--- permutation-sequence/index.md | 4 +--- permutations-ii/index.md | 4 +--- permutations/index.md | 4 +--- plus-one/index.md | 4 +--- populating-next-right-pointers-in-each-node-ii/index.md | 4 +--- populating-next-right-pointers-in-each-node/index.md | 4 +--- powx-n/index.md | 4 +--- .../index.md | 4 +--- read-n-characters-given-read4/index.md | 4 +--- recover-binary-search-tree/index.md | 4 +--- regular-expression-matching/index.md | 4 +--- remove-duplicates-from-sorted-array-ii/index.md | 4 +--- remove-duplicates-from-sorted-array/index.md | 4 +--- remove-duplicates-from-sorted-list-ii/index.md | 4 +--- remove-duplicates-from-sorted-list/index.md | 4 +--- remove-element/index.md | 4 +--- remove-nth-node-from-end-of-list/index.md | 4 +--- reorder-list/index.md | 4 +--- repeated-dna-sequences/index.md | 4 +--- restore-ip-addresses/index.md | 4 +--- reverse-bits/index.md | 4 +--- reverse-integer/index.md | 4 +--- reverse-linked-list-ii/index.md | 4 +--- reverse-nodes-in-k-group/index.md | 4 +--- reverse-words-in-a-string-ii/index.md | 4 +--- reverse-words-in-a-string/index.md | 4 +--- roman-to-integer/index.md | 4 +--- rotate-array/index.md | 4 +--- rotate-image/index.md | 4 +--- rotate-list/index.md | 4 +--- same-tree/index.md | 4 +--- scramble-string/index.md | 4 +--- search-a-2d-matrix/index.md | 4 +--- search-for-a-range/index.md | 4 +--- search-in-rotated-sorted-array-ii/index.md | 4 +--- search-in-rotated-sorted-array/index.md | 4 +--- search-insert-position/index.md | 4 +--- set-matrix-zeroes/index.md | 4 +--- simplify-path/index.md | 4 +--- single-number-ii/index.md | 4 +--- single-number/index.md | 4 +--- skeleton.sh | 4 +--- sort-colors/index.md | 4 +--- sort-list/index.md | 4 +--- spiral-matrix-ii/index.md | 4 +--- spiral-matrix/index.md | 4 +--- sqrtx/index.md | 4 +--- string-to-integer-atoi/index.md | 4 +--- subsets-ii/index.md | 4 +--- subsets/index.md | 4 +--- substring-with-concatenation-of-all-words/index.md | 4 +--- sudoku-solver/index.md | 4 +--- sum-root-to-leaf-numbers/index.md | 4 +--- surrounded-regions/index.md | 4 +--- swap-nodes-in-pairs/index.md | 4 +--- symmetric-tree/index.md | 4 +--- text-justification/index.md | 4 +--- trapping-rain-water/index.md | 4 +--- triangle/index.md | 4 +--- two-sum-ii-input-array-is-sorted/index.md | 4 +--- two-sum-iii-data-structure-design/index.md | 4 +--- two-sum/index.md | 5 +---- unique-binary-search-trees-ii/index.md | 4 +--- unique-binary-search-trees/index.md | 4 +--- unique-paths-ii/index.md | 4 +--- unique-paths/index.md | 4 +--- valid-number/index.md | 4 +--- valid-palindrome/index.md | 4 +--- valid-parentheses/index.md | 4 +--- valid-sudoku/index.md | 4 +--- validate-binary-search-tree/index.md | 4 +--- wildcard-matching/index.md | 4 +--- word-break-ii/index.md | 4 +--- word-break/index.md | 4 +--- word-ladder-ii/index.md | 4 +--- word-ladder/index.md | 4 +--- word-search/index.md | 4 +--- zigzag-conversion/index.md | 4 +--- 188 files changed, 186 insertions(+), 563 deletions(-) delete mode 100644 .gitmodules delete mode 160000 _includes/_root diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 3fdb97a..0000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "_includes/_root"] - path = _includes/_root - url = https://github.com/tg123/leetcode.git - branch = gh-pages diff --git a/3sum-closest/index.md b/3sum-closest/index.md index b002b14..a61508f 100644 --- a/3sum-closest/index.md +++ b/3sum-closest/index.md @@ -4,6 +4,4 @@ title: 3Sum Closest date: 2014-12-29 00:26:24 +0800 leetcode_id: 16 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/3sum/index.md b/3sum/index.md index 672d40d..9dd6a94 100644 --- a/3sum/index.md +++ b/3sum/index.md @@ -4,6 +4,4 @@ title: 3Sum date: 2015-02-16 11:19:43 +0800 leetcode_id: 15 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/4sum/index.md b/4sum/index.md index 525eb28..eee2d52 100644 --- a/4sum/index.md +++ b/4sum/index.md @@ -4,6 +4,4 @@ title: 4Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 18 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/_includes/_root b/_includes/_root deleted file mode 160000 index ea68d4f..0000000 --- a/_includes/_root +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ea68d4f9bea0987ab941317d254d2ee9addf38d2 diff --git a/_layouts/solution.html b/_layouts/solution.html index 40448c2..dc81d53 100644 --- a/_layouts/solution.html +++ b/_layouts/solution.html @@ -2,7 +2,6 @@ layout: default --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_source = {{leetcode_name | append: '/Solution.java' | prepend: '_root/'}} %} {% assign leetcode_url = {{leetcode_name | prepend: 'https://oj.leetcode.com/problems/'}} %} {% assign github_url = {{leetcode_name | prepend: 'https://github.com/tg123/leetcode/blob/gh-pages/' }} %} {% assign github_source_url = {{leetcode_name | prepend: 'https://github.com/tg123/leetcode/blob/gh-pages/' | append: '/Solution.java' }} %} @@ -22,7 +21,7 @@

{{ page.title }}

Source code Read on Github

{% highlight java linenos %} -{% include {{leetcode_source}} %} +{% include_relative Solution.java %} {% endhighlight %}
diff --git a/add-binary/index.md b/add-binary/index.md index 1739a6a..c55f9da 100644 --- a/add-binary/index.md +++ b/add-binary/index.md @@ -4,6 +4,4 @@ title: Add Binary date: 2014-12-29 00:26:24 +0800 leetcode_id: 67 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/add-two-numbers/index.md b/add-two-numbers/index.md index 1c974fd..e1cd9d7 100644 --- a/add-two-numbers/index.md +++ b/add-two-numbers/index.md @@ -4,6 +4,4 @@ title: Add Two Numbers date: 2014-12-29 00:26:24 +0800 leetcode_id: 2 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/anagrams/index.md b/anagrams/index.md index bd03345..2dea82f 100644 --- a/anagrams/index.md +++ b/anagrams/index.md @@ -4,6 +4,4 @@ title: Anagrams date: 2015-01-18 23:39:27 +0800 leetcode_id: 49 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/balanced-binary-tree/index.md b/balanced-binary-tree/index.md index 3ad8f6a..6661ffd 100644 --- a/balanced-binary-tree/index.md +++ b/balanced-binary-tree/index.md @@ -4,6 +4,4 @@ title: Balanced Binary Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 110 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/best-time-to-buy-and-sell-stock-ii/index.md b/best-time-to-buy-and-sell-stock-ii/index.md index f784aca..0b00142 100644 --- a/best-time-to-buy-and-sell-stock-ii/index.md +++ b/best-time-to-buy-and-sell-stock-ii/index.md @@ -4,6 +4,4 @@ title: Best Time to Buy and Sell Stock II date: 2014-12-29 00:26:24 +0800 leetcode_id: 122 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/best-time-to-buy-and-sell-stock-iii/index.md b/best-time-to-buy-and-sell-stock-iii/index.md index 20c985e..e2e62d9 100644 --- a/best-time-to-buy-and-sell-stock-iii/index.md +++ b/best-time-to-buy-and-sell-stock-iii/index.md @@ -4,6 +4,4 @@ title: Best Time to Buy and Sell Stock III date: 2014-12-29 00:26:24 +0800 leetcode_id: 123 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/best-time-to-buy-and-sell-stock-iv/index.md b/best-time-to-buy-and-sell-stock-iv/index.md index 4e1ba22..697d7b5 100644 --- a/best-time-to-buy-and-sell-stock-iv/index.md +++ b/best-time-to-buy-and-sell-stock-iv/index.md @@ -4,6 +4,4 @@ title: Best Time to Buy and Sell Stock IV date: 2015-03-08 01:04:43 +0800 leetcode_id: 188 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/best-time-to-buy-and-sell-stock/index.md b/best-time-to-buy-and-sell-stock/index.md index 1489be2..9e56f38 100644 --- a/best-time-to-buy-and-sell-stock/index.md +++ b/best-time-to-buy-and-sell-stock/index.md @@ -4,6 +4,4 @@ title: Best Time to Buy and Sell Stock date: 2014-12-29 00:26:24 +0800 leetcode_id: 121 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-search-tree-iterator/index.md b/binary-search-tree-iterator/index.md index 228521d..23988ba 100644 --- a/binary-search-tree-iterator/index.md +++ b/binary-search-tree-iterator/index.md @@ -4,6 +4,4 @@ title: Binary Search Tree Iterator date: 2015-01-03 03:26:48 +0800 leetcode_id: 173 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-inorder-traversal/index.md b/binary-tree-inorder-traversal/index.md index db33f61..35dfbb1 100644 --- a/binary-tree-inorder-traversal/index.md +++ b/binary-tree-inorder-traversal/index.md @@ -4,6 +4,4 @@ title: Binary Tree Inorder Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 94 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-level-order-traversal-ii/index.md b/binary-tree-level-order-traversal-ii/index.md index fe6ac33..8621a95 100644 --- a/binary-tree-level-order-traversal-ii/index.md +++ b/binary-tree-level-order-traversal-ii/index.md @@ -4,6 +4,4 @@ title: Binary Tree Level Order Traversal II date: 2014-12-29 00:26:24 +0800 leetcode_id: 107 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-level-order-traversal/index.md b/binary-tree-level-order-traversal/index.md index ad1f022..32e1904 100644 --- a/binary-tree-level-order-traversal/index.md +++ b/binary-tree-level-order-traversal/index.md @@ -4,6 +4,4 @@ title: Binary Tree Level Order Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 102 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-maximum-path-sum/index.md b/binary-tree-maximum-path-sum/index.md index bc62599..128f0d3 100644 --- a/binary-tree-maximum-path-sum/index.md +++ b/binary-tree-maximum-path-sum/index.md @@ -4,6 +4,4 @@ title: Binary Tree Maximum Path Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 124 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-postorder-traversal/index.md b/binary-tree-postorder-traversal/index.md index fb76b55..3492494 100644 --- a/binary-tree-postorder-traversal/index.md +++ b/binary-tree-postorder-traversal/index.md @@ -4,6 +4,4 @@ title: Binary Tree Postorder Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 145 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-preorder-traversal/index.md b/binary-tree-preorder-traversal/index.md index e7e8dc4..c423e45 100644 --- a/binary-tree-preorder-traversal/index.md +++ b/binary-tree-preorder-traversal/index.md @@ -4,6 +4,4 @@ title: Binary Tree Preorder Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 144 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-right-side-view/index.md b/binary-tree-right-side-view/index.md index 3d08d66..e558487 100644 --- a/binary-tree-right-side-view/index.md +++ b/binary-tree-right-side-view/index.md @@ -4,6 +4,4 @@ title: Binary Tree Right Side View date: 2015-04-03 21:32:41 +0800 leetcode_id: 199 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-upside-down/index.md b/binary-tree-upside-down/index.md index 0e28334..1cea6ff 100644 --- a/binary-tree-upside-down/index.md +++ b/binary-tree-upside-down/index.md @@ -4,6 +4,4 @@ title: Binary Tree Upside Down date: 2014-11-18 01:45:13 +0800 leetcode_id: 156 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/binary-tree-zigzag-level-order-traversal/index.md b/binary-tree-zigzag-level-order-traversal/index.md index 5fc8762..b310481 100644 --- a/binary-tree-zigzag-level-order-traversal/index.md +++ b/binary-tree-zigzag-level-order-traversal/index.md @@ -4,6 +4,4 @@ title: Binary Tree Zigzag Level Order Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 103 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/candy/index.md b/candy/index.md index b78c5d6..997e539 100644 --- a/candy/index.md +++ b/candy/index.md @@ -4,6 +4,4 @@ title: Candy date: 2014-12-29 00:26:24 +0800 leetcode_id: 135 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/climbing-stairs/index.md b/climbing-stairs/index.md index d6a084e..30af6b4 100644 --- a/climbing-stairs/index.md +++ b/climbing-stairs/index.md @@ -4,6 +4,4 @@ title: Climbing Stairs date: 2014-12-29 00:26:24 +0800 leetcode_id: 70 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/clone-graph/index.md b/clone-graph/index.md index f98f6fe..07acdaf 100644 --- a/clone-graph/index.md +++ b/clone-graph/index.md @@ -4,6 +4,4 @@ title: Clone Graph date: 2014-12-29 00:26:24 +0800 leetcode_id: 133 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/combination-sum-ii/index.md b/combination-sum-ii/index.md index 5e1d25e..7f71dce 100644 --- a/combination-sum-ii/index.md +++ b/combination-sum-ii/index.md @@ -4,6 +4,4 @@ title: Combination Sum II date: 2014-12-29 00:26:24 +0800 leetcode_id: 40 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/combination-sum/index.md b/combination-sum/index.md index 7f3a9ae..53421c6 100644 --- a/combination-sum/index.md +++ b/combination-sum/index.md @@ -4,6 +4,4 @@ title: Combination Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 39 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/combinations/index.md b/combinations/index.md index 175a482..d46668c 100644 --- a/combinations/index.md +++ b/combinations/index.md @@ -4,6 +4,4 @@ title: Combinations date: 2014-12-29 00:26:24 +0800 leetcode_id: 77 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/compare-version-numbers/index.md b/compare-version-numbers/index.md index 0273b92..7151bae 100644 --- a/compare-version-numbers/index.md +++ b/compare-version-numbers/index.md @@ -4,6 +4,4 @@ title: Compare Version Numbers date: 2015-01-21 17:26:33 +0800 leetcode_id: 165 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md index 7247604..6497884 100644 --- a/construct-binary-tree-from-inorder-and-postorder-traversal/index.md +++ b/construct-binary-tree-from-inorder-and-postorder-traversal/index.md @@ -4,6 +4,4 @@ title: Construct Binary Tree from Inorder and Postorder Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 106 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md index d7037b3..b2274d2 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/index.md +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/index.md @@ -4,6 +4,4 @@ title: Construct Binary Tree from Preorder and Inorder Traversal date: 2014-12-29 00:26:24 +0800 leetcode_id: 105 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/container-with-most-water/index.md b/container-with-most-water/index.md index 06de669..b1e611a 100644 --- a/container-with-most-water/index.md +++ b/container-with-most-water/index.md @@ -4,6 +4,4 @@ title: Container With Most Water date: 2014-12-29 00:26:24 +0800 leetcode_id: 11 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/convert-sorted-array-to-binary-search-tree/index.md b/convert-sorted-array-to-binary-search-tree/index.md index e6dee32..c904583 100644 --- a/convert-sorted-array-to-binary-search-tree/index.md +++ b/convert-sorted-array-to-binary-search-tree/index.md @@ -4,6 +4,4 @@ title: Convert Sorted Array to Binary Search Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 108 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/convert-sorted-list-to-binary-search-tree/index.md b/convert-sorted-list-to-binary-search-tree/index.md index dd62fa9..cd4386e 100644 --- a/convert-sorted-list-to-binary-search-tree/index.md +++ b/convert-sorted-list-to-binary-search-tree/index.md @@ -4,6 +4,4 @@ title: Convert Sorted List to Binary Search Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 109 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/copy-list-with-random-pointer/index.md b/copy-list-with-random-pointer/index.md index 78f85e1..f88396b 100644 --- a/copy-list-with-random-pointer/index.md +++ b/copy-list-with-random-pointer/index.md @@ -4,6 +4,4 @@ title: Copy List with Random Pointer date: 2014-12-29 00:26:24 +0800 leetcode_id: 138 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/count-and-say/index.md b/count-and-say/index.md index 555c64e..79806a3 100644 --- a/count-and-say/index.md +++ b/count-and-say/index.md @@ -4,6 +4,4 @@ title: Count and Say date: 2014-12-29 00:26:24 +0800 leetcode_id: 38 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/decode-ways/index.md b/decode-ways/index.md index 6461d68..7530ef7 100644 --- a/decode-ways/index.md +++ b/decode-ways/index.md @@ -4,6 +4,4 @@ title: Decode Ways date: 2014-12-29 00:26:24 +0800 leetcode_id: 91 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/distinct-subsequences/index.md b/distinct-subsequences/index.md index b1da625..d59963f 100644 --- a/distinct-subsequences/index.md +++ b/distinct-subsequences/index.md @@ -4,6 +4,4 @@ title: Distinct Subsequences date: 2014-12-29 00:26:24 +0800 leetcode_id: 115 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/divide-two-integers/index.md b/divide-two-integers/index.md index c4b00cf..b68a336 100644 --- a/divide-two-integers/index.md +++ b/divide-two-integers/index.md @@ -4,6 +4,4 @@ title: Divide Two Integers date: 2014-12-29 00:26:24 +0800 leetcode_id: 29 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/dungeon-game/index.md b/dungeon-game/index.md index a4fc3bc..07c9818 100644 --- a/dungeon-game/index.md +++ b/dungeon-game/index.md @@ -4,6 +4,4 @@ title: Dungeon Game date: 2015-01-21 18:54:25 +0800 leetcode_id: 174 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/edit-distance/index.md b/edit-distance/index.md index 07ac2b6..d28c003 100644 --- a/edit-distance/index.md +++ b/edit-distance/index.md @@ -4,6 +4,4 @@ title: Edit Distance date: 2014-12-29 00:26:24 +0800 leetcode_id: 72 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/evaluate-reverse-polish-notation/index.md b/evaluate-reverse-polish-notation/index.md index 664becc..c773d91 100644 --- a/evaluate-reverse-polish-notation/index.md +++ b/evaluate-reverse-polish-notation/index.md @@ -4,6 +4,4 @@ title: Evaluate Reverse Polish Notation date: 2014-12-29 00:26:24 +0800 leetcode_id: 150 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/excel-sheet-column-number/index.md b/excel-sheet-column-number/index.md index 9f7aaed..b325899 100644 --- a/excel-sheet-column-number/index.md +++ b/excel-sheet-column-number/index.md @@ -4,6 +4,4 @@ title: Excel Sheet Column Number date: 2015-01-21 17:54:45 +0800 leetcode_id: 171 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/excel-sheet-column-title/index.md b/excel-sheet-column-title/index.md index 4806a7f..2923fb9 100644 --- a/excel-sheet-column-title/index.md +++ b/excel-sheet-column-title/index.md @@ -4,6 +4,4 @@ title: Excel Sheet Column Title date: 2015-01-21 17:53:50 +0800 leetcode_id: 168 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/factorial-trailing-zeroes/index.md b/factorial-trailing-zeroes/index.md index ea0c193..733104d 100644 --- a/factorial-trailing-zeroes/index.md +++ b/factorial-trailing-zeroes/index.md @@ -4,6 +4,4 @@ title: Factorial Trailing Zeroes date: 2015-01-03 03:36:44 +0800 leetcode_id: 172 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/find-minimum-in-rotated-sorted-array-ii/index.md b/find-minimum-in-rotated-sorted-array-ii/index.md index ac995a8..def2bf9 100644 --- a/find-minimum-in-rotated-sorted-array-ii/index.md +++ b/find-minimum-in-rotated-sorted-array-ii/index.md @@ -4,6 +4,4 @@ title: Find Minimum in Rotated Sorted Array II date: 2014-12-29 00:26:24 +0800 leetcode_id: 154 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/find-minimum-in-rotated-sorted-array/index.md b/find-minimum-in-rotated-sorted-array/index.md index 466d818..255c2f1 100644 --- a/find-minimum-in-rotated-sorted-array/index.md +++ b/find-minimum-in-rotated-sorted-array/index.md @@ -4,6 +4,4 @@ title: Find Minimum in Rotated Sorted Array date: 2014-12-29 00:26:24 +0800 leetcode_id: 153 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/find-peak-element/index.md b/find-peak-element/index.md index a88f70d..693fe39 100644 --- a/find-peak-element/index.md +++ b/find-peak-element/index.md @@ -4,6 +4,4 @@ title: Find Peak Element date: 2014-12-29 00:26:24 +0800 leetcode_id: 162 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/first-missing-positive/index.md b/first-missing-positive/index.md index 60d7cd5..9ee8208 100644 --- a/first-missing-positive/index.md +++ b/first-missing-positive/index.md @@ -4,6 +4,4 @@ title: First Missing Positive date: 2014-12-29 00:26:24 +0800 leetcode_id: 41 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/flatten-binary-tree-to-linked-list/index.md b/flatten-binary-tree-to-linked-list/index.md index 03c81ec..e9beaf3 100644 --- a/flatten-binary-tree-to-linked-list/index.md +++ b/flatten-binary-tree-to-linked-list/index.md @@ -4,6 +4,4 @@ title: Flatten Binary Tree to Linked List date: 2014-12-29 00:26:24 +0800 leetcode_id: 114 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/fraction-to-recurring-decimal/index.md b/fraction-to-recurring-decimal/index.md index 813fdef..5295755 100644 --- a/fraction-to-recurring-decimal/index.md +++ b/fraction-to-recurring-decimal/index.md @@ -4,6 +4,4 @@ title: Fraction to Recurring Decimal date: 2015-01-21 17:46:10 +0800 leetcode_id: 166 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/gas-station/index.md b/gas-station/index.md index 0f36f94..b053213 100644 --- a/gas-station/index.md +++ b/gas-station/index.md @@ -4,6 +4,4 @@ title: Gas Station date: 2014-12-29 00:26:24 +0800 leetcode_id: 134 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/generate-parentheses/index.md b/generate-parentheses/index.md index 0e86418..6773a80 100644 --- a/generate-parentheses/index.md +++ b/generate-parentheses/index.md @@ -4,6 +4,4 @@ title: Generate Parentheses date: 2014-12-29 00:26:24 +0800 leetcode_id: 22 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/gray-code/index.md b/gray-code/index.md index 25c0864..319da9d 100644 --- a/gray-code/index.md +++ b/gray-code/index.md @@ -4,6 +4,4 @@ title: Gray Code date: 2015-02-13 00:44:38 +0800 leetcode_id: 89 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/house-robber/index.md b/house-robber/index.md index 80859c3..cae3cf8 100644 --- a/house-robber/index.md +++ b/house-robber/index.md @@ -4,6 +4,4 @@ title: House Robber date: 2015-03-31 20:10:39 +0800 leetcode_id: 198 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/implement-strstr/index.md b/implement-strstr/index.md index 193d19d..22fb12e 100644 --- a/implement-strstr/index.md +++ b/implement-strstr/index.md @@ -4,6 +4,4 @@ title: Implement strStr() date: 2014-12-29 00:26:24 +0800 leetcode_id: 28 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/insert-interval/index.md b/insert-interval/index.md index 373a916..5f9b647 100644 --- a/insert-interval/index.md +++ b/insert-interval/index.md @@ -4,6 +4,4 @@ title: Insert Interval date: 2014-12-29 00:26:24 +0800 leetcode_id: 57 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/insertion-sort-list/index.md b/insertion-sort-list/index.md index dd80efc..94888a1 100644 --- a/insertion-sort-list/index.md +++ b/insertion-sort-list/index.md @@ -4,6 +4,4 @@ title: Insertion Sort List date: 2014-12-29 00:26:24 +0800 leetcode_id: 147 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/integer-to-roman/index.md b/integer-to-roman/index.md index 8247fb7..dac44a6 100644 --- a/integer-to-roman/index.md +++ b/integer-to-roman/index.md @@ -4,6 +4,4 @@ title: Integer to Roman date: 2014-12-29 00:26:24 +0800 leetcode_id: 12 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/interleaving-string/index.md b/interleaving-string/index.md index b02643e..cdc5248 100644 --- a/interleaving-string/index.md +++ b/interleaving-string/index.md @@ -4,6 +4,4 @@ title: Interleaving String date: 2014-12-29 00:26:24 +0800 leetcode_id: 97 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/intersection-of-two-linked-lists/index.md b/intersection-of-two-linked-lists/index.md index 8b96b46..54e299d 100644 --- a/intersection-of-two-linked-lists/index.md +++ b/intersection-of-two-linked-lists/index.md @@ -4,6 +4,4 @@ title: Intersection of Two Linked Lists date: 2014-12-29 00:26:24 +0800 leetcode_id: 160 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/jump-game-ii/index.md b/jump-game-ii/index.md index 0dcabcf..89100fd 100644 --- a/jump-game-ii/index.md +++ b/jump-game-ii/index.md @@ -4,6 +4,4 @@ title: Jump Game II date: 2014-12-29 00:26:24 +0800 leetcode_id: 45 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/jump-game/index.md b/jump-game/index.md index a85e7aa..b11ba12 100644 --- a/jump-game/index.md +++ b/jump-game/index.md @@ -4,6 +4,4 @@ title: Jump Game date: 2014-12-29 00:26:24 +0800 leetcode_id: 55 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/largest-number/index.md b/largest-number/index.md index 82c2ac1..d9076ab 100644 --- a/largest-number/index.md +++ b/largest-number/index.md @@ -4,6 +4,4 @@ title: Largest Number date: 2015-01-21 17:33:39 +0800 leetcode_id: 179 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/largest-rectangle-in-histogram/index.md b/largest-rectangle-in-histogram/index.md index 0fe1e19..944918e 100644 --- a/largest-rectangle-in-histogram/index.md +++ b/largest-rectangle-in-histogram/index.md @@ -4,6 +4,4 @@ title: Largest Rectangle in Histogram date: 2014-12-29 00:26:24 +0800 leetcode_id: 84 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/length-of-last-word/index.md b/length-of-last-word/index.md index b7075e0..7e402d7 100644 --- a/length-of-last-word/index.md +++ b/length-of-last-word/index.md @@ -4,6 +4,4 @@ title: Length of Last Word date: 2014-12-29 00:26:24 +0800 leetcode_id: 58 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/letter-combinations-of-a-phone-number/index.md b/letter-combinations-of-a-phone-number/index.md index 8c9632e..3a8fd7b 100644 --- a/letter-combinations-of-a-phone-number/index.md +++ b/letter-combinations-of-a-phone-number/index.md @@ -4,6 +4,4 @@ title: Letter Combinations of a Phone Number date: 2015-01-18 03:28:07 +0800 leetcode_id: 17 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/linked-list-cycle-ii/index.md b/linked-list-cycle-ii/index.md index e872762..fc84214 100644 --- a/linked-list-cycle-ii/index.md +++ b/linked-list-cycle-ii/index.md @@ -4,6 +4,4 @@ title: Linked List Cycle II date: 2014-12-29 00:26:24 +0800 leetcode_id: 142 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/linked-list-cycle/index.md b/linked-list-cycle/index.md index 7829596..9d057f3 100644 --- a/linked-list-cycle/index.md +++ b/linked-list-cycle/index.md @@ -4,6 +4,4 @@ title: Linked List Cycle date: 2014-12-29 00:26:24 +0800 leetcode_id: 141 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-common-prefix/index.md b/longest-common-prefix/index.md index 78fc4f3..28d695c 100644 --- a/longest-common-prefix/index.md +++ b/longest-common-prefix/index.md @@ -4,6 +4,4 @@ title: Longest Common Prefix date: 2014-12-29 00:26:24 +0800 leetcode_id: 14 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-consecutive-sequence/index.md b/longest-consecutive-sequence/index.md index 5553e49..cbfb422 100644 --- a/longest-consecutive-sequence/index.md +++ b/longest-consecutive-sequence/index.md @@ -4,6 +4,4 @@ title: Longest Consecutive Sequence date: 2014-12-29 00:26:24 +0800 leetcode_id: 128 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-palindromic-substring/index.md b/longest-palindromic-substring/index.md index 2f5b645..a5b9457 100644 --- a/longest-palindromic-substring/index.md +++ b/longest-palindromic-substring/index.md @@ -4,6 +4,4 @@ title: Longest Palindromic Substring date: 2014-12-29 00:26:24 +0800 leetcode_id: 5 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-substring-with-at-most-two-distinct-characters/index.md b/longest-substring-with-at-most-two-distinct-characters/index.md index c1b808a..598f768 100644 --- a/longest-substring-with-at-most-two-distinct-characters/index.md +++ b/longest-substring-with-at-most-two-distinct-characters/index.md @@ -4,6 +4,4 @@ title: Longest Substring with At Most Two Distinct Characters date: 2014-12-29 00:26:24 +0800 leetcode_id: 159 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-substring-without-repeating-characters/index.md b/longest-substring-without-repeating-characters/index.md index 868db91..8ca0b66 100644 --- a/longest-substring-without-repeating-characters/index.md +++ b/longest-substring-without-repeating-characters/index.md @@ -4,6 +4,4 @@ title: Longest Substring Without Repeating Characters date: 2014-12-29 00:26:24 +0800 leetcode_id: 3 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/longest-valid-parentheses/index.md b/longest-valid-parentheses/index.md index b010d76..a52481a 100644 --- a/longest-valid-parentheses/index.md +++ b/longest-valid-parentheses/index.md @@ -4,6 +4,4 @@ title: Longest Valid Parentheses date: 2014-12-29 00:26:24 +0800 leetcode_id: 32 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/lru-cache/index.md b/lru-cache/index.md index 3197346..1cc0bc0 100644 --- a/lru-cache/index.md +++ b/lru-cache/index.md @@ -4,6 +4,4 @@ title: LRU Cache date: 2014-12-29 00:26:24 +0800 leetcode_id: 146 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/majority-element/index.md b/majority-element/index.md index eafead8..e64ca8a 100644 --- a/majority-element/index.md +++ b/majority-element/index.md @@ -4,6 +4,4 @@ title: Majority Element date: 2015-01-03 03:53:03 +0800 leetcode_id: 169 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/max-points-on-a-line/index.md b/max-points-on-a-line/index.md index b237c67..559fd3e 100644 --- a/max-points-on-a-line/index.md +++ b/max-points-on-a-line/index.md @@ -4,6 +4,4 @@ title: Max Points on a Line date: 2014-12-29 00:26:24 +0800 leetcode_id: 149 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/maximal-rectangle/index.md b/maximal-rectangle/index.md index c04459b..72eee5b 100644 --- a/maximal-rectangle/index.md +++ b/maximal-rectangle/index.md @@ -4,6 +4,4 @@ title: Maximal Rectangle date: 2014-12-29 00:26:24 +0800 leetcode_id: 85 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/maximum-depth-of-binary-tree/index.md b/maximum-depth-of-binary-tree/index.md index 6b3b4c2..ab5b064 100644 --- a/maximum-depth-of-binary-tree/index.md +++ b/maximum-depth-of-binary-tree/index.md @@ -4,6 +4,4 @@ title: Maximum Depth of Binary Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 104 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/maximum-gap/index.md b/maximum-gap/index.md index b87796f..698f2c3 100644 --- a/maximum-gap/index.md +++ b/maximum-gap/index.md @@ -4,6 +4,4 @@ title: Maximum Gap date: 2014-12-29 00:26:24 +0800 leetcode_id: 164 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/maximum-product-subarray/index.md b/maximum-product-subarray/index.md index b62014f..c5ac74a 100644 --- a/maximum-product-subarray/index.md +++ b/maximum-product-subarray/index.md @@ -4,6 +4,4 @@ title: Maximum Product Subarray date: 2014-09-24 23:57:39 +0800 leetcode_id: 152 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/maximum-subarray/index.md b/maximum-subarray/index.md index e91f5a3..a500d33 100644 --- a/maximum-subarray/index.md +++ b/maximum-subarray/index.md @@ -4,6 +4,4 @@ title: Maximum Subarray date: 2014-12-29 00:26:24 +0800 leetcode_id: 53 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/median-of-two-sorted-arrays/index.md b/median-of-two-sorted-arrays/index.md index 8c294ec..d520b30 100644 --- a/median-of-two-sorted-arrays/index.md +++ b/median-of-two-sorted-arrays/index.md @@ -4,6 +4,4 @@ title: Median of Two Sorted Arrays date: 2014-12-29 00:26:24 +0800 leetcode_id: 4 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/merge-intervals/index.md b/merge-intervals/index.md index 59998c2..255fc48 100644 --- a/merge-intervals/index.md +++ b/merge-intervals/index.md @@ -4,6 +4,4 @@ title: Merge Intervals date: 2014-12-29 00:26:24 +0800 leetcode_id: 56 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/merge-k-sorted-lists/index.md b/merge-k-sorted-lists/index.md index 756ff07..2d796fd 100644 --- a/merge-k-sorted-lists/index.md +++ b/merge-k-sorted-lists/index.md @@ -4,6 +4,4 @@ title: Merge k Sorted Lists date: 2014-12-29 00:26:24 +0800 leetcode_id: 23 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/merge-sorted-array/index.md b/merge-sorted-array/index.md index c78f3e7..4775d36 100644 --- a/merge-sorted-array/index.md +++ b/merge-sorted-array/index.md @@ -4,6 +4,4 @@ title: Merge Sorted Array date: 2015-02-13 00:34:52 +0800 leetcode_id: 88 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/merge-two-sorted-lists/index.md b/merge-two-sorted-lists/index.md index 15358d2..53c2277 100644 --- a/merge-two-sorted-lists/index.md +++ b/merge-two-sorted-lists/index.md @@ -4,6 +4,4 @@ title: Merge Two Sorted Lists date: 2014-12-29 00:26:24 +0800 leetcode_id: 21 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/min-stack/index.md b/min-stack/index.md index 4e7143f..d1114de 100644 --- a/min-stack/index.md +++ b/min-stack/index.md @@ -4,6 +4,4 @@ title: Min Stack date: 2014-11-18 00:59:34 +0800 leetcode_id: 155 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/minimum-depth-of-binary-tree/index.md b/minimum-depth-of-binary-tree/index.md index f97d54f..35d2a27 100644 --- a/minimum-depth-of-binary-tree/index.md +++ b/minimum-depth-of-binary-tree/index.md @@ -4,6 +4,4 @@ title: Minimum Depth of Binary Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 111 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/minimum-path-sum/index.md b/minimum-path-sum/index.md index 0ad9aac..56e4fa4 100644 --- a/minimum-path-sum/index.md +++ b/minimum-path-sum/index.md @@ -4,6 +4,4 @@ title: Minimum Path Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 64 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/minimum-window-substring/index.md b/minimum-window-substring/index.md index ee153da..e2509fc 100644 --- a/minimum-window-substring/index.md +++ b/minimum-window-substring/index.md @@ -4,6 +4,4 @@ title: Minimum Window Substring date: 2014-12-29 00:26:24 +0800 leetcode_id: 76 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/missing-ranges/index.md b/missing-ranges/index.md index 3a15aa8..ab887ea 100644 --- a/missing-ranges/index.md +++ b/missing-ranges/index.md @@ -4,6 +4,4 @@ title: Missing Ranges date: 2014-12-29 00:26:24 +0800 leetcode_id: 163 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/multiply-strings/index.md b/multiply-strings/index.md index d23bae4..b2b7520 100644 --- a/multiply-strings/index.md +++ b/multiply-strings/index.md @@ -4,6 +4,4 @@ title: Multiply Strings date: 2014-12-29 00:26:24 +0800 leetcode_id: 43 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/n-queens-ii/index.md b/n-queens-ii/index.md index aa106c3..120f7ad 100644 --- a/n-queens-ii/index.md +++ b/n-queens-ii/index.md @@ -4,6 +4,4 @@ title: N-Queens II date: 2014-12-29 00:26:24 +0800 leetcode_id: 52 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/n-queens/index.md b/n-queens/index.md index 979bab5..5ca314c 100644 --- a/n-queens/index.md +++ b/n-queens/index.md @@ -4,6 +4,4 @@ title: N-Queens date: 2014-12-29 00:26:24 +0800 leetcode_id: 51 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/next-permutation/index.md b/next-permutation/index.md index 2484374..c7ef7be 100644 --- a/next-permutation/index.md +++ b/next-permutation/index.md @@ -4,6 +4,4 @@ title: Next Permutation date: 2014-12-29 00:26:24 +0800 leetcode_id: 31 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/number-of-1-bits/index.md b/number-of-1-bits/index.md index ea4fbeb..a1078c5 100644 --- a/number-of-1-bits/index.md +++ b/number-of-1-bits/index.md @@ -4,6 +4,4 @@ title: Number of 1 Bits date: 2015-03-10 12:33:10 +0800 leetcode_id: 191 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/number-of-islands/index.md b/number-of-islands/index.md index 75835c5..5d3dc64 100644 --- a/number-of-islands/index.md +++ b/number-of-islands/index.md @@ -4,6 +4,4 @@ title: Number of Islands date: 2015-04-08 13:28:15+08:00 leetcode_id: 200 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/one-edit-distance/index.md b/one-edit-distance/index.md index ff2ebd1..ec336b3 100644 --- a/one-edit-distance/index.md +++ b/one-edit-distance/index.md @@ -4,6 +4,4 @@ title: One Edit Distance date: 2014-12-29 00:26:24 +0800 leetcode_id: 161 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/palindrome-number/index.md b/palindrome-number/index.md index b86af95..1c393a4 100644 --- a/palindrome-number/index.md +++ b/palindrome-number/index.md @@ -4,6 +4,4 @@ title: Palindrome Number date: 2015-02-16 17:43:10 +0800 leetcode_id: 9 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/palindrome-partitioning-ii/index.md b/palindrome-partitioning-ii/index.md index 92c6d4e..5f02f13 100644 --- a/palindrome-partitioning-ii/index.md +++ b/palindrome-partitioning-ii/index.md @@ -4,6 +4,4 @@ title: Palindrome Partitioning II date: 2014-12-29 00:26:24 +0800 leetcode_id: 132 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/palindrome-partitioning/index.md b/palindrome-partitioning/index.md index 167101f..6c9767d 100644 --- a/palindrome-partitioning/index.md +++ b/palindrome-partitioning/index.md @@ -4,6 +4,4 @@ title: Palindrome Partitioning date: 2014-12-29 00:26:24 +0800 leetcode_id: 131 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/partition-list/index.md b/partition-list/index.md index 348fba0..95205bb 100644 --- a/partition-list/index.md +++ b/partition-list/index.md @@ -4,6 +4,4 @@ title: Partition List date: 2014-12-29 00:26:24 +0800 leetcode_id: 86 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/pascals-triangle-ii/index.md b/pascals-triangle-ii/index.md index e7573fe..2df0e89 100644 --- a/pascals-triangle-ii/index.md +++ b/pascals-triangle-ii/index.md @@ -4,6 +4,4 @@ title: Pascal's Triangle II date: 2014-12-29 00:26:24 +0800 leetcode_id: 119 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/pascals-triangle/index.md b/pascals-triangle/index.md index c9b49ef..b4877b3 100644 --- a/pascals-triangle/index.md +++ b/pascals-triangle/index.md @@ -4,6 +4,4 @@ title: Pascal's Triangle date: 2014-12-29 00:26:24 +0800 leetcode_id: 118 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/path-sum-ii/index.md b/path-sum-ii/index.md index 1bb6614..1a725cd 100644 --- a/path-sum-ii/index.md +++ b/path-sum-ii/index.md @@ -4,6 +4,4 @@ title: Path Sum II date: 2014-12-29 00:26:24 +0800 leetcode_id: 113 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/path-sum/index.md b/path-sum/index.md index 73781f3..16491c4 100644 --- a/path-sum/index.md +++ b/path-sum/index.md @@ -4,6 +4,4 @@ title: Path Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 112 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/permutation-sequence/index.md b/permutation-sequence/index.md index 1956c27..a5192a4 100644 --- a/permutation-sequence/index.md +++ b/permutation-sequence/index.md @@ -4,6 +4,4 @@ title: Permutation Sequence date: 2014-12-29 00:26:24 +0800 leetcode_id: 60 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/permutations-ii/index.md b/permutations-ii/index.md index c81f239..84036ab 100644 --- a/permutations-ii/index.md +++ b/permutations-ii/index.md @@ -4,6 +4,4 @@ title: Permutations II date: 2014-12-29 00:26:24 +0800 leetcode_id: 47 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/permutations/index.md b/permutations/index.md index 6b9e57c..a6708ec 100644 --- a/permutations/index.md +++ b/permutations/index.md @@ -4,6 +4,4 @@ title: Permutations date: 2014-12-29 00:26:24 +0800 leetcode_id: 46 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/plus-one/index.md b/plus-one/index.md index e04f238..102b564 100644 --- a/plus-one/index.md +++ b/plus-one/index.md @@ -4,6 +4,4 @@ title: Plus One date: 2014-12-29 00:26:24 +0800 leetcode_id: 66 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/populating-next-right-pointers-in-each-node-ii/index.md b/populating-next-right-pointers-in-each-node-ii/index.md index 262be19..f020fa6 100644 --- a/populating-next-right-pointers-in-each-node-ii/index.md +++ b/populating-next-right-pointers-in-each-node-ii/index.md @@ -4,6 +4,4 @@ title: Populating Next Right Pointers in Each Node II date: 2014-12-29 00:26:24 +0800 leetcode_id: 117 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/populating-next-right-pointers-in-each-node/index.md b/populating-next-right-pointers-in-each-node/index.md index da292c2..8b48d7a 100644 --- a/populating-next-right-pointers-in-each-node/index.md +++ b/populating-next-right-pointers-in-each-node/index.md @@ -4,6 +4,4 @@ title: Populating Next Right Pointers in Each Node date: 2014-12-29 00:26:24 +0800 leetcode_id: 116 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/powx-n/index.md b/powx-n/index.md index 3abcfb9..d0f44ed 100644 --- a/powx-n/index.md +++ b/powx-n/index.md @@ -4,6 +4,4 @@ title: Pow(x, n) date: 2014-12-29 00:26:24 +0800 leetcode_id: 50 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/read-n-characters-given-read4-ii-call-multiple-times/index.md b/read-n-characters-given-read4-ii-call-multiple-times/index.md index cc2df63..52a6c51 100644 --- a/read-n-characters-given-read4-ii-call-multiple-times/index.md +++ b/read-n-characters-given-read4-ii-call-multiple-times/index.md @@ -4,6 +4,4 @@ title: Read N Characters Given Read4 II - Call multiple times date: 2014-12-29 00:26:24 +0800 leetcode_id: 158 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/read-n-characters-given-read4/index.md b/read-n-characters-given-read4/index.md index 19a4f5e..111133f 100644 --- a/read-n-characters-given-read4/index.md +++ b/read-n-characters-given-read4/index.md @@ -4,6 +4,4 @@ title: Read N Characters Given Read4 date: 2014-12-29 00:26:24 +0800 leetcode_id: 157 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/recover-binary-search-tree/index.md b/recover-binary-search-tree/index.md index 52ba332..3025e4c 100644 --- a/recover-binary-search-tree/index.md +++ b/recover-binary-search-tree/index.md @@ -4,6 +4,4 @@ title: Recover Binary Search Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 99 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/regular-expression-matching/index.md b/regular-expression-matching/index.md index 309dc29..3a07abc 100644 --- a/regular-expression-matching/index.md +++ b/regular-expression-matching/index.md @@ -4,6 +4,4 @@ title: Regular Expression Matching date: 2014-12-29 00:26:24 +0800 leetcode_id: 10 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-duplicates-from-sorted-array-ii/index.md b/remove-duplicates-from-sorted-array-ii/index.md index e1f66e9..6150623 100644 --- a/remove-duplicates-from-sorted-array-ii/index.md +++ b/remove-duplicates-from-sorted-array-ii/index.md @@ -4,6 +4,4 @@ title: Remove Duplicates from Sorted Array II date: 2014-12-29 00:26:24 +0800 leetcode_id: 80 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-duplicates-from-sorted-array/index.md b/remove-duplicates-from-sorted-array/index.md index 4393d88..e09cbc4 100644 --- a/remove-duplicates-from-sorted-array/index.md +++ b/remove-duplicates-from-sorted-array/index.md @@ -4,6 +4,4 @@ title: Remove Duplicates from Sorted Array date: 2014-12-29 00:26:24 +0800 leetcode_id: 26 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-duplicates-from-sorted-list-ii/index.md b/remove-duplicates-from-sorted-list-ii/index.md index 4d64ac1..0356ee4 100644 --- a/remove-duplicates-from-sorted-list-ii/index.md +++ b/remove-duplicates-from-sorted-list-ii/index.md @@ -4,6 +4,4 @@ title: Remove Duplicates from Sorted List II date: 2014-12-29 00:26:24 +0800 leetcode_id: 82 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-duplicates-from-sorted-list/index.md b/remove-duplicates-from-sorted-list/index.md index dbe930c..58728b3 100644 --- a/remove-duplicates-from-sorted-list/index.md +++ b/remove-duplicates-from-sorted-list/index.md @@ -4,6 +4,4 @@ title: Remove Duplicates from Sorted List date: 2014-12-29 00:26:24 +0800 leetcode_id: 83 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-element/index.md b/remove-element/index.md index e868ba8..1a5ba21 100644 --- a/remove-element/index.md +++ b/remove-element/index.md @@ -4,6 +4,4 @@ title: Remove Element date: 2014-12-29 00:26:24 +0800 leetcode_id: 27 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/remove-nth-node-from-end-of-list/index.md b/remove-nth-node-from-end-of-list/index.md index fb3fa2e..d604ea1 100644 --- a/remove-nth-node-from-end-of-list/index.md +++ b/remove-nth-node-from-end-of-list/index.md @@ -4,6 +4,4 @@ title: Remove Nth Node From End of List date: 2014-12-29 00:26:24 +0800 leetcode_id: 19 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reorder-list/index.md b/reorder-list/index.md index 0d40da5..e339b43 100644 --- a/reorder-list/index.md +++ b/reorder-list/index.md @@ -4,6 +4,4 @@ title: Reorder List date: 2014-12-29 00:26:24 +0800 leetcode_id: 143 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/repeated-dna-sequences/index.md b/repeated-dna-sequences/index.md index dc814f3..5e6ae50 100644 --- a/repeated-dna-sequences/index.md +++ b/repeated-dna-sequences/index.md @@ -4,6 +4,4 @@ title: Repeated DNA Sequences date: 2015-03-08 01:16:06 +0800 leetcode_id: 187 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/restore-ip-addresses/index.md b/restore-ip-addresses/index.md index 36710a2..99e6e2b 100644 --- a/restore-ip-addresses/index.md +++ b/restore-ip-addresses/index.md @@ -4,6 +4,4 @@ title: Restore IP Addresses date: 2014-12-29 00:26:24 +0800 leetcode_id: 93 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-bits/index.md b/reverse-bits/index.md index e5ef1de..bfffd23 100644 --- a/reverse-bits/index.md +++ b/reverse-bits/index.md @@ -4,6 +4,4 @@ title: Reverse Bits date: 2015-03-07 19:36:21 +0800 leetcode_id: 190 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-integer/index.md b/reverse-integer/index.md index 813d566..e47927f 100644 --- a/reverse-integer/index.md +++ b/reverse-integer/index.md @@ -4,6 +4,4 @@ title: Reverse Integer date: 2015-01-18 03:14:54 +0800 leetcode_id: 7 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-linked-list-ii/index.md b/reverse-linked-list-ii/index.md index d65f42e..2245e9a 100644 --- a/reverse-linked-list-ii/index.md +++ b/reverse-linked-list-ii/index.md @@ -4,6 +4,4 @@ title: Reverse Linked List II date: 2014-12-29 00:26:24 +0800 leetcode_id: 92 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-nodes-in-k-group/index.md b/reverse-nodes-in-k-group/index.md index b034ef5..5c1be88 100644 --- a/reverse-nodes-in-k-group/index.md +++ b/reverse-nodes-in-k-group/index.md @@ -4,6 +4,4 @@ title: Reverse Nodes in k-Group date: 2014-12-29 00:26:24 +0800 leetcode_id: 25 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-words-in-a-string-ii/index.md b/reverse-words-in-a-string-ii/index.md index 55be95a..b13b207 100644 --- a/reverse-words-in-a-string-ii/index.md +++ b/reverse-words-in-a-string-ii/index.md @@ -4,6 +4,4 @@ title: Reverse Words in a String II date: 2015-02-03 14:42:33 +0800 leetcode_id: 186 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/reverse-words-in-a-string/index.md b/reverse-words-in-a-string/index.md index 88bd05e..b6aab81 100644 --- a/reverse-words-in-a-string/index.md +++ b/reverse-words-in-a-string/index.md @@ -4,6 +4,4 @@ title: Reverse Words in a String date: 2015-01-19 00:08:01 +0800 leetcode_id: 151 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/roman-to-integer/index.md b/roman-to-integer/index.md index d99b286..3076c43 100644 --- a/roman-to-integer/index.md +++ b/roman-to-integer/index.md @@ -4,6 +4,4 @@ title: Roman to Integer date: 2014-12-29 00:26:24 +0800 leetcode_id: 13 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/rotate-array/index.md b/rotate-array/index.md index fd5a686..85eeb33 100644 --- a/rotate-array/index.md +++ b/rotate-array/index.md @@ -4,6 +4,4 @@ title: Rotate Array date: 2015-03-04 01:39:57 +0800 leetcode_id: 189 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/rotate-image/index.md b/rotate-image/index.md index f8a2719..7fcfdce 100644 --- a/rotate-image/index.md +++ b/rotate-image/index.md @@ -4,6 +4,4 @@ title: Rotate Image date: 2014-12-29 00:26:24 +0800 leetcode_id: 48 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/rotate-list/index.md b/rotate-list/index.md index 45258b7..7998645 100644 --- a/rotate-list/index.md +++ b/rotate-list/index.md @@ -4,6 +4,4 @@ title: Rotate List date: 2014-12-29 00:26:24 +0800 leetcode_id: 61 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/same-tree/index.md b/same-tree/index.md index b782b27..1c0024b 100644 --- a/same-tree/index.md +++ b/same-tree/index.md @@ -4,6 +4,4 @@ title: Same Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 100 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/scramble-string/index.md b/scramble-string/index.md index d53fff5..7744138 100644 --- a/scramble-string/index.md +++ b/scramble-string/index.md @@ -4,6 +4,4 @@ title: Scramble String date: 2014-12-29 00:26:24 +0800 leetcode_id: 87 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/search-a-2d-matrix/index.md b/search-a-2d-matrix/index.md index daf935f..20286a4 100644 --- a/search-a-2d-matrix/index.md +++ b/search-a-2d-matrix/index.md @@ -4,6 +4,4 @@ title: Search a 2D Matrix date: 2014-12-29 00:26:24 +0800 leetcode_id: 74 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/search-for-a-range/index.md b/search-for-a-range/index.md index dd9c71b..b60cba3 100644 --- a/search-for-a-range/index.md +++ b/search-for-a-range/index.md @@ -4,6 +4,4 @@ title: Search for a Range date: 2014-12-29 00:26:24 +0800 leetcode_id: 34 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/search-in-rotated-sorted-array-ii/index.md b/search-in-rotated-sorted-array-ii/index.md index 8139bb6..81594de 100644 --- a/search-in-rotated-sorted-array-ii/index.md +++ b/search-in-rotated-sorted-array-ii/index.md @@ -4,6 +4,4 @@ title: Search in Rotated Sorted Array II date: 2014-12-29 00:26:24 +0800 leetcode_id: 81 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/search-in-rotated-sorted-array/index.md b/search-in-rotated-sorted-array/index.md index 2215282..6167729 100644 --- a/search-in-rotated-sorted-array/index.md +++ b/search-in-rotated-sorted-array/index.md @@ -4,6 +4,4 @@ title: Search in Rotated Sorted Array date: 2014-12-29 00:26:24 +0800 leetcode_id: 33 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/search-insert-position/index.md b/search-insert-position/index.md index 303314f..ec3700e 100644 --- a/search-insert-position/index.md +++ b/search-insert-position/index.md @@ -4,6 +4,4 @@ title: Search Insert Position date: 2014-12-29 00:26:24 +0800 leetcode_id: 35 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/set-matrix-zeroes/index.md b/set-matrix-zeroes/index.md index ab5f6ca..7e0f220 100644 --- a/set-matrix-zeroes/index.md +++ b/set-matrix-zeroes/index.md @@ -4,6 +4,4 @@ title: Set Matrix Zeroes date: 2014-12-29 00:26:24 +0800 leetcode_id: 73 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/simplify-path/index.md b/simplify-path/index.md index cd0d98a..924e27c 100644 --- a/simplify-path/index.md +++ b/simplify-path/index.md @@ -4,6 +4,4 @@ title: Simplify Path date: 2015-01-29 15:17:38 +0800 leetcode_id: 71 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/single-number-ii/index.md b/single-number-ii/index.md index 49a8ae8..b8d1972 100644 --- a/single-number-ii/index.md +++ b/single-number-ii/index.md @@ -4,6 +4,4 @@ title: Single Number II date: 2014-12-29 00:26:24 +0800 leetcode_id: 137 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/single-number/index.md b/single-number/index.md index 8f9175d..d639686 100644 --- a/single-number/index.md +++ b/single-number/index.md @@ -4,6 +4,4 @@ title: Single Number date: 2014-12-29 00:26:24 +0800 leetcode_id: 136 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/skeleton.sh b/skeleton.sh index c249e26..fa3c0c7 100755 --- a/skeleton.sh +++ b/skeleton.sh @@ -20,9 +20,7 @@ title: FIXME date: $now leetcode_id: FIXME --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} EOL diff --git a/sort-colors/index.md b/sort-colors/index.md index 81eaad5..ea77fbb 100644 --- a/sort-colors/index.md +++ b/sort-colors/index.md @@ -4,6 +4,4 @@ title: Sort Colors date: 2015-01-22 01:52:46 +0800 leetcode_id: 75 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/sort-list/index.md b/sort-list/index.md index f6ac98d..9dcd802 100644 --- a/sort-list/index.md +++ b/sort-list/index.md @@ -4,6 +4,4 @@ title: Sort List date: 2014-12-29 00:26:24 +0800 leetcode_id: 148 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/spiral-matrix-ii/index.md b/spiral-matrix-ii/index.md index fa9813a..e624bf8 100644 --- a/spiral-matrix-ii/index.md +++ b/spiral-matrix-ii/index.md @@ -4,6 +4,4 @@ title: Spiral Matrix II date: 2014-12-29 00:26:24 +0800 leetcode_id: 59 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/spiral-matrix/index.md b/spiral-matrix/index.md index 99c8006..e68647e 100644 --- a/spiral-matrix/index.md +++ b/spiral-matrix/index.md @@ -4,6 +4,4 @@ title: Spiral Matrix date: 2014-12-29 00:26:24 +0800 leetcode_id: 54 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/sqrtx/index.md b/sqrtx/index.md index 31cc78c..909dcc2 100644 --- a/sqrtx/index.md +++ b/sqrtx/index.md @@ -4,6 +4,4 @@ title: Sqrt(x) date: 2015-01-18 23:48:07 +0800 leetcode_id: 69 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/string-to-integer-atoi/index.md b/string-to-integer-atoi/index.md index 70484c6..3304230 100644 --- a/string-to-integer-atoi/index.md +++ b/string-to-integer-atoi/index.md @@ -4,6 +4,4 @@ title: String to Integer (atoi) date: 2014-12-29 00:26:24 +0800 leetcode_id: 8 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/subsets-ii/index.md b/subsets-ii/index.md index a8e086a..d3de772 100644 --- a/subsets-ii/index.md +++ b/subsets-ii/index.md @@ -4,6 +4,4 @@ title: Subsets II date: 2015-02-13 01:14:40 +0800 leetcode_id: 90 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/subsets/index.md b/subsets/index.md index e7401c2..4264933 100644 --- a/subsets/index.md +++ b/subsets/index.md @@ -4,6 +4,4 @@ title: Subsets date: 2015-02-13 01:10:10 +0800 leetcode_id: 78 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/substring-with-concatenation-of-all-words/index.md b/substring-with-concatenation-of-all-words/index.md index 3827ff6..54e5fe3 100644 --- a/substring-with-concatenation-of-all-words/index.md +++ b/substring-with-concatenation-of-all-words/index.md @@ -4,6 +4,4 @@ title: Substring with Concatenation of All Words date: 2014-12-29 00:26:24 +0800 leetcode_id: 30 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/sudoku-solver/index.md b/sudoku-solver/index.md index 533f205..4953517 100644 --- a/sudoku-solver/index.md +++ b/sudoku-solver/index.md @@ -4,6 +4,4 @@ title: Sudoku Solver date: 2014-12-29 00:26:24 +0800 leetcode_id: 37 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/sum-root-to-leaf-numbers/index.md b/sum-root-to-leaf-numbers/index.md index ebd2a0f..ed920b0 100644 --- a/sum-root-to-leaf-numbers/index.md +++ b/sum-root-to-leaf-numbers/index.md @@ -4,6 +4,4 @@ title: Sum Root to Leaf Numbers date: 2015-01-16 16:07:02 -0500 leetcode_id: 129 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/surrounded-regions/index.md b/surrounded-regions/index.md index 0cabbe2..7e48167 100644 --- a/surrounded-regions/index.md +++ b/surrounded-regions/index.md @@ -4,6 +4,4 @@ title: Surrounded Regions date: 2014-12-29 00:26:24 +0800 leetcode_id: 130 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/swap-nodes-in-pairs/index.md b/swap-nodes-in-pairs/index.md index 409f48c..dcbf2db 100644 --- a/swap-nodes-in-pairs/index.md +++ b/swap-nodes-in-pairs/index.md @@ -4,6 +4,4 @@ title: Swap Nodes in Pairs date: 2014-12-29 00:26:24 +0800 leetcode_id: 24 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/symmetric-tree/index.md b/symmetric-tree/index.md index cbce220..bde57f8 100644 --- a/symmetric-tree/index.md +++ b/symmetric-tree/index.md @@ -4,6 +4,4 @@ title: Symmetric Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 101 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/text-justification/index.md b/text-justification/index.md index 11f1826..2990eb3 100644 --- a/text-justification/index.md +++ b/text-justification/index.md @@ -4,6 +4,4 @@ title: Text Justification date: 2014-12-29 00:26:24 +0800 leetcode_id: 68 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/trapping-rain-water/index.md b/trapping-rain-water/index.md index cfa47c3..db8107d 100644 --- a/trapping-rain-water/index.md +++ b/trapping-rain-water/index.md @@ -4,6 +4,4 @@ title: Trapping Rain Water date: 2014-12-29 00:26:24 +0800 leetcode_id: 42 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/triangle/index.md b/triangle/index.md index 15935f4..ad75db1 100644 --- a/triangle/index.md +++ b/triangle/index.md @@ -4,6 +4,4 @@ title: Triangle date: 2015-03-20 12:51:52 +0800 leetcode_id: 120 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/two-sum-ii-input-array-is-sorted/index.md b/two-sum-ii-input-array-is-sorted/index.md index fd0423c..624ff8c 100644 --- a/two-sum-ii-input-array-is-sorted/index.md +++ b/two-sum-ii-input-array-is-sorted/index.md @@ -4,6 +4,4 @@ title: Two Sum II - Input array is sorted date: 2015-01-23 12:45:49 +0800 leetcode_id: 167 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/two-sum-iii-data-structure-design/index.md b/two-sum-iii-data-structure-design/index.md index 56f45d1..bd983e9 100644 --- a/two-sum-iii-data-structure-design/index.md +++ b/two-sum-iii-data-structure-design/index.md @@ -4,6 +4,4 @@ title: Two Sum III - Data structure design date: 2015-01-21 18:05:09 +0800 leetcode_id: 170 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/two-sum/index.md b/two-sum/index.md index c4e3e82..df8f548 100644 --- a/two-sum/index.md +++ b/two-sum/index.md @@ -4,7 +4,4 @@ title: Two Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 1 leetcode_id: 1 ---- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/unique-binary-search-trees-ii/index.md b/unique-binary-search-trees-ii/index.md index e6ab9be..4947ffe 100644 --- a/unique-binary-search-trees-ii/index.md +++ b/unique-binary-search-trees-ii/index.md @@ -4,6 +4,4 @@ title: Unique Binary Search Trees II date: 2014-12-29 00:26:24 +0800 leetcode_id: 95 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/unique-binary-search-trees/index.md b/unique-binary-search-trees/index.md index b25c64f..697affa 100644 --- a/unique-binary-search-trees/index.md +++ b/unique-binary-search-trees/index.md @@ -4,6 +4,4 @@ title: Unique Binary Search Trees date: 2014-12-29 00:26:24 +0800 leetcode_id: 96 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/unique-paths-ii/index.md b/unique-paths-ii/index.md index 124cfbe..9b6ffcb 100644 --- a/unique-paths-ii/index.md +++ b/unique-paths-ii/index.md @@ -4,6 +4,4 @@ title: Unique Paths II date: 2014-12-29 00:26:24 +0800 leetcode_id: 63 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/unique-paths/index.md b/unique-paths/index.md index 33a3fc3..e2a8bf3 100644 --- a/unique-paths/index.md +++ b/unique-paths/index.md @@ -4,6 +4,4 @@ title: Unique Paths date: 2014-12-29 00:26:24 +0800 leetcode_id: 62 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/valid-number/index.md b/valid-number/index.md index 9d189a4..f9cf82c 100644 --- a/valid-number/index.md +++ b/valid-number/index.md @@ -4,6 +4,4 @@ title: Valid Number date: 2014-12-29 00:26:24 +0800 leetcode_id: 65 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/valid-palindrome/index.md b/valid-palindrome/index.md index 69bfcac..bccb9c0 100644 --- a/valid-palindrome/index.md +++ b/valid-palindrome/index.md @@ -4,6 +4,4 @@ title: Valid Palindrome date: 2014-12-29 00:26:24 +0800 leetcode_id: 125 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/valid-parentheses/index.md b/valid-parentheses/index.md index 0a0e687..22f698f 100644 --- a/valid-parentheses/index.md +++ b/valid-parentheses/index.md @@ -4,6 +4,4 @@ title: Valid Parentheses date: 2014-12-29 00:26:24 +0800 leetcode_id: 20 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/valid-sudoku/index.md b/valid-sudoku/index.md index ff1e19f..5ee9111 100644 --- a/valid-sudoku/index.md +++ b/valid-sudoku/index.md @@ -4,6 +4,4 @@ title: Valid Sudoku date: 2014-12-29 00:26:24 +0800 leetcode_id: 36 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/validate-binary-search-tree/index.md b/validate-binary-search-tree/index.md index 716ea48..4b79c08 100644 --- a/validate-binary-search-tree/index.md +++ b/validate-binary-search-tree/index.md @@ -4,6 +4,4 @@ title: Validate Binary Search Tree date: 2014-12-29 00:26:24 +0800 leetcode_id: 98 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/wildcard-matching/index.md b/wildcard-matching/index.md index 7e5947e..59064c9 100644 --- a/wildcard-matching/index.md +++ b/wildcard-matching/index.md @@ -4,6 +4,4 @@ title: Wildcard Matching date: 2014-12-29 00:26:24 +0800 leetcode_id: 44 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/word-break-ii/index.md b/word-break-ii/index.md index 1f81e4d..31eeab9 100644 --- a/word-break-ii/index.md +++ b/word-break-ii/index.md @@ -4,6 +4,4 @@ title: Word Break II date: 2014-12-29 00:26:24 +0800 leetcode_id: 140 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/word-break/index.md b/word-break/index.md index 69f62cf..784221f 100644 --- a/word-break/index.md +++ b/word-break/index.md @@ -4,6 +4,4 @@ title: Word Break date: 2014-12-29 00:26:24 +0800 leetcode_id: 139 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/word-ladder-ii/index.md b/word-ladder-ii/index.md index a76b3dd..e5f6699 100644 --- a/word-ladder-ii/index.md +++ b/word-ladder-ii/index.md @@ -4,6 +4,4 @@ title: Word Ladder II date: 2014-12-29 00:26:24 +0800 leetcode_id: 126 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/word-ladder/index.md b/word-ladder/index.md index 9458dce..e0df4cf 100644 --- a/word-ladder/index.md +++ b/word-ladder/index.md @@ -4,6 +4,4 @@ title: Word Ladder date: 2014-12-29 00:26:24 +0800 leetcode_id: 127 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/word-search/index.md b/word-search/index.md index 9ee737d..753116f 100644 --- a/word-search/index.md +++ b/word-search/index.md @@ -4,6 +4,4 @@ title: Word Search date: 2014-12-29 00:26:24 +0800 leetcode_id: 79 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} diff --git a/zigzag-conversion/index.md b/zigzag-conversion/index.md index 1778316..20eb8c6 100644 --- a/zigzag-conversion/index.md +++ b/zigzag-conversion/index.md @@ -4,6 +4,4 @@ title: ZigZag Conversion date: 2014-12-29 00:26:24 +0800 leetcode_id: 6 --- -{% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %} -{% include {{leetcode_readme}} %} +{% include_relative README.md %} From a9c1c10d4981dbed7027e665875a77eccc369bdb Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 15:07:31 +0800 Subject: [PATCH 120/195] new github style gemfile --- Gemfile | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 053c27d..f85f962 100644 --- a/Gemfile +++ b/Gemfile @@ -1,2 +1,7 @@ source 'https://rubygems.org' -gem 'github-pages' + +require 'json' +require 'open-uri' +versions = JSON.parse(open('https://pages.github.com/versions.json').read) + +gem 'github-pages', versions['github-pages'] From 882d7b01851f42de658fdd71ea042e2d3c2aae3f Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 15:07:58 +0800 Subject: [PATCH 121/195] make jekyll happy --- number-of-islands/Solution.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/number-of-islands/Solution.java b/number-of-islands/Solution.java index a772d48..905ee55 100644 --- a/number-of-islands/Solution.java +++ b/number-of-islands/Solution.java @@ -16,7 +16,7 @@ void travel(int x, int y, final int mx, final int my, char[][] grid, boolean[][] visited[x][y] = true; - for(int[] xy: new int[][]{{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}}){ + for(int[] xy: new int[][]{ {x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1} }){ int _x = xy[0]; int _y = xy[1]; From 93d8fc2f38c759e1b26b33e791dc3024ecfeffb5 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 15:08:46 +0800 Subject: [PATCH 122/195] change to LeetCode (was Leetcode) --- _config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/_config.yml b/_config.yml index bacb619..8383411 100644 --- a/_config.yml +++ b/_config.yml @@ -1,6 +1,6 @@ -title: Leetcode solutions by tgic +title: LeetCode solutions by tgic email: farmer1992@gmail.com -description: "Leetcode solutions by tgic" +description: "LeetCode java solutions by tgic" github_username: tg123 markdown: redcarpet From 69716885d534d7e8c6f49a83033a3b86b8e9c59b Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Apr 2015 15:34:46 +0800 Subject: [PATCH 123/195] fix bag index file --- two-sum/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum/index.md b/two-sum/index.md index df8f548..4ccaf5a 100644 --- a/two-sum/index.md +++ b/two-sum/index.md @@ -3,5 +3,5 @@ layout: solution title: Two Sum date: 2014-12-29 00:26:24 +0800 leetcode_id: 1 -leetcode_id: 1 +--- {% include_relative README.md %} From bbdc8b4780529ecbf5ba2107f58c71e6f6d92513 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 21 Apr 2015 01:19:28 +0800 Subject: [PATCH 124/195] add bit and range numbers --- bitwise-and-of-numbers-range/README.md | 0 bitwise-and-of-numbers-range/Solution.java | 22 ++++++++++++++++++++++ bitwise-and-of-numbers-range/index.md | 7 +++++++ 3 files changed, 29 insertions(+) create mode 100644 bitwise-and-of-numbers-range/README.md create mode 100644 bitwise-and-of-numbers-range/Solution.java create mode 100644 bitwise-and-of-numbers-range/index.md diff --git a/bitwise-and-of-numbers-range/README.md b/bitwise-and-of-numbers-range/README.md new file mode 100644 index 0000000..e69de29 diff --git a/bitwise-and-of-numbers-range/Solution.java b/bitwise-and-of-numbers-range/Solution.java new file mode 100644 index 0000000..f0d8d81 --- /dev/null +++ b/bitwise-and-of-numbers-range/Solution.java @@ -0,0 +1,22 @@ +public class Solution { + public int rangeBitwiseAnd(int m, int n) { + final int SIZE = Integer.SIZE; + + long[] POW = new long[SIZE + 1]; + + for(int i = 0; i < SIZE; i++){ + POW[i] = (long)Math.pow(2, i); + } + + for(int i = SIZE; i > 0; i--){ + if(POW[i - 1] <= m && m < POW[i]){ + if(POW[i - 1] <= n && n < POW[i]){ + long p = POW[i - 1]; + return (int)p | rangeBitwiseAnd((int)(m & (p - 1)), (int)(n & (p - 1))); + } + } + } + + return 0; + } +} diff --git a/bitwise-and-of-numbers-range/index.md b/bitwise-and-of-numbers-range/index.md new file mode 100644 index 0000000..0041852 --- /dev/null +++ b/bitwise-and-of-numbers-range/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Bitwise AND of Numbers Range +date: 2015-04-21 01:17:47+08:00 +leetcode_id: 201 +--- +{% include_relative README.md %} From 1aa30251ccfad2e793539441c4842197068e2c6d Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 22 Apr 2015 12:34:48 +0800 Subject: [PATCH 125/195] happy today --- happy-number/README.md | 0 happy-number/Solution.java | 33 +++++++++++++++++++++++++++++++++ happy-number/index.md | 7 +++++++ 3 files changed, 40 insertions(+) create mode 100644 happy-number/README.md create mode 100644 happy-number/Solution.java create mode 100644 happy-number/index.md diff --git a/happy-number/README.md b/happy-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/happy-number/Solution.java b/happy-number/Solution.java new file mode 100644 index 0000000..c31546f --- /dev/null +++ b/happy-number/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + + int trans(int n){ + int s = 0; + + do{ + int t = n % 10; + + s += t * t; + + n /= 10; + + } while(n > 0); + + return s; + } + + public boolean isHappy(int n) { + Set s = new HashSet<>(); + + for(;;) { + + n = trans(n); + + if(n == 1) return true; + + if(s.contains(n)) return false; + + s.add(n); + } + + } +} diff --git a/happy-number/index.md b/happy-number/index.md new file mode 100644 index 0000000..3053af5 --- /dev/null +++ b/happy-number/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Happy Number +date: 2015-04-22 12:33:21+08:00 +leetcode_id: 202 +--- +{% include_relative README.md %} From e9ab17e4cdb4d30213f7e8fbd58c5cfec9b9bf8d Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 23 Apr 2015 11:39:56 +0800 Subject: [PATCH 126/195] add remove ele from linkedlist --- remove-linked-list-elements/README.md | 0 remove-linked-list-elements/Solution.java | 20 ++++++++++++++++++++ remove-linked-list-elements/index.md | 7 +++++++ 3 files changed, 27 insertions(+) create mode 100644 remove-linked-list-elements/README.md create mode 100644 remove-linked-list-elements/Solution.java create mode 100644 remove-linked-list-elements/index.md diff --git a/remove-linked-list-elements/README.md b/remove-linked-list-elements/README.md new file mode 100644 index 0000000..e69de29 diff --git a/remove-linked-list-elements/Solution.java b/remove-linked-list-elements/Solution.java new file mode 100644 index 0000000..c106a1e --- /dev/null +++ b/remove-linked-list-elements/Solution.java @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode removeElements(ListNode head, int val) { + + if(head == null) return null; + + if(head.val == val) return removeElements(head.next, val); + + head.next = removeElements(head.next, val); + + return head; + } +} diff --git a/remove-linked-list-elements/index.md b/remove-linked-list-elements/index.md new file mode 100644 index 0000000..421610a --- /dev/null +++ b/remove-linked-list-elements/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Remove Linked List Elements +date: 2015-04-23 11:38:34+08:00 +leetcode_id: 203 +--- +{% include_relative README.md %} From e695da465790ad77f110396f3d7d0dda1e255b55 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 27 Apr 2015 16:40:41 +0800 Subject: [PATCH 127/195] add count primes --- count-primes/README.md | 0 count-primes/Solution.java | 21 +++++++++++++++++++++ count-primes/index.md | 7 +++++++ 3 files changed, 28 insertions(+) create mode 100644 count-primes/README.md create mode 100644 count-primes/Solution.java create mode 100644 count-primes/index.md diff --git a/count-primes/README.md b/count-primes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/count-primes/Solution.java b/count-primes/Solution.java new file mode 100644 index 0000000..13c7394 --- /dev/null +++ b/count-primes/Solution.java @@ -0,0 +1,21 @@ +public class Solution { + public int countPrimes(int n) { + + if(n < 2) return 0; + + BitSet b = new BitSet(); + + b.set(0); + b.set(1); + + for(int p = 2; p * 2 < n ; p = b.nextClearBit(p + 1)){ + for(int i = 2; p * i < n ;i++){ + b.set(p * i); + } + } + + b.flip(0, n); + + return b.cardinality(); + } +} diff --git a/count-primes/index.md b/count-primes/index.md new file mode 100644 index 0000000..8feafa0 --- /dev/null +++ b/count-primes/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Count Primes +date: 2015-04-27 16:39:19+08:00 +leetcode_id: 204 +--- +{% include_relative README.md %} From e7cb7930d806cc12f386721d94f4f3f729667eaa Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 29 Apr 2015 12:09:06 +0800 Subject: [PATCH 128/195] add isomorphfic strings --- isomorphic-strings/README.md | 0 isomorphic-strings/Solution.java | 33 ++++++++++++++++++++++++++++++++ isomorphic-strings/index.md | 7 +++++++ 3 files changed, 40 insertions(+) create mode 100644 isomorphic-strings/README.md create mode 100644 isomorphic-strings/Solution.java create mode 100644 isomorphic-strings/index.md diff --git a/isomorphic-strings/README.md b/isomorphic-strings/README.md new file mode 100644 index 0000000..e69de29 diff --git a/isomorphic-strings/Solution.java b/isomorphic-strings/Solution.java new file mode 100644 index 0000000..ad85b88 --- /dev/null +++ b/isomorphic-strings/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + + boolean isIsomorphic(char[] S, char[] T) { + char[] MAP = new char[256]; + + for(int i = 0; i < S.length; i++) { + + if(MAP[(int)S[i]] == 0) { + // not mapped + MAP[(int)S[i]] = T[i]; + } else { + + if ( MAP[(int)S[i]] != T[i]) { + return false; + } + } + + } + + return true; + } + + public boolean isIsomorphic(String s, String t) { + + char[] S = s.toCharArray(); + char[] T = t.toCharArray(); + + if(S.length != T.length) return false; + + return isIsomorphic(S, T) && isIsomorphic(T, S); + + } +} diff --git a/isomorphic-strings/index.md b/isomorphic-strings/index.md new file mode 100644 index 0000000..a04ce3e --- /dev/null +++ b/isomorphic-strings/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Isomorphic Strings +date: 2015-04-29 12:07:38+08:00 +leetcode_id: 205 +--- +{% include_relative README.md %} From 08e85ae717b1814561fa4c6aab39b6b596858abb Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 5 May 2015 11:48:40 +0800 Subject: [PATCH 129/195] add reverse linked list --- reverse-linked-list/README.md | 0 reverse-linked-list/Solution.java | 24 ++++++++++++++++++++++++ reverse-linked-list/index.md | 7 +++++++ 3 files changed, 31 insertions(+) create mode 100644 reverse-linked-list/README.md create mode 100644 reverse-linked-list/Solution.java create mode 100644 reverse-linked-list/index.md diff --git a/reverse-linked-list/README.md b/reverse-linked-list/README.md new file mode 100644 index 0000000..e69de29 diff --git a/reverse-linked-list/Solution.java b/reverse-linked-list/Solution.java new file mode 100644 index 0000000..91aba69 --- /dev/null +++ b/reverse-linked-list/Solution.java @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +public class Solution { + public ListNode reverseList(ListNode head) { + + if(head == null) return null; + if(head.next == null) return head; + + ListNode tail = head.next; + ListNode reversed = reverseList(head.next); + + tail.next = head; + + head.next = null; + + return reversed; + } +} diff --git a/reverse-linked-list/index.md b/reverse-linked-list/index.md new file mode 100644 index 0000000..eead8fb --- /dev/null +++ b/reverse-linked-list/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Reverse Linked List +date: 2015-05-05 11:37:08+08:00 +leetcode_id: 206 +--- +{% include_relative README.md %} From 364ca5b13cdab4dc22b8f3eca472e44f57716aed Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 5 May 2015 11:59:41 +0800 Subject: [PATCH 130/195] link to reverse linked list --- reorder-list/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reorder-list/README.md b/reorder-list/README.md index deade0e..8230038 100644 --- a/reorder-list/README.md +++ b/reorder-list/README.md @@ -8,7 +8,7 @@ reorder can be achieved via ## Some O(n) method to deal with a linked list -### Reverse a linked list +### [Reverse a linked list](../reverse-linked-list) 1. walk through the linked list 1. set `node.next` to `prev` From 3f169e0c0d0ec2541d92220cafb72aae1b3fd8ea Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 7 May 2015 00:51:31 +0800 Subject: [PATCH 131/195] add course sched --- course-schedule/README.md | 0 course-schedule/Solution.java | 61 +++++++++++++++++++++++++++++++++++ course-schedule/index.md | 7 ++++ 3 files changed, 68 insertions(+) create mode 100644 course-schedule/README.md create mode 100644 course-schedule/Solution.java create mode 100644 course-schedule/index.md diff --git a/course-schedule/README.md b/course-schedule/README.md new file mode 100644 index 0000000..e69de29 diff --git a/course-schedule/Solution.java b/course-schedule/Solution.java new file mode 100644 index 0000000..7200c27 --- /dev/null +++ b/course-schedule/Solution.java @@ -0,0 +1,61 @@ +public class Solution { + + static class Vertex { + + int id; + + Vertex(int id){ + this.id = id; + } + + Set in = new HashSet<>(); + Set out = new HashSet<>(); + + boolean isSink(){ + return out.isEmpty(); + } + } + + Vertex safe(Vertex[] G, int id){ + if(G[id] == null){ + G[id] = new Vertex(id); + } + + return G[id]; + } + + public boolean canFinish(int numCourses, int[][] prerequisites) { + + Vertex[] G = new Vertex[numCourses]; + + for(int[] p : prerequisites){ + safe(G, p[0]).out.add(p[1]); + safe(G, p[1]).in.add(p[0]); + } + + Set S = Arrays.stream(G) + .filter(v -> v != null) + .collect(Collectors.toSet()); + + + loop: + while(!S.isEmpty()){ + + for(Vertex v : S){ + if(v.isSink()){ + S.remove(v); + + for(int i : v.in){ + G[i].out.remove(v.id); + } + + continue loop; + } + } + + return false; + } + + return true; + } +} diff --git a/course-schedule/index.md b/course-schedule/index.md new file mode 100644 index 0000000..6c4da2d --- /dev/null +++ b/course-schedule/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Course Schedule +date: 2015-05-07 00:48:21+08:00 +leetcode_id: 207 +--- +{% include_relative README.md %} From 042bf0b9a28c86e5681827b2deee103b1fae70a8 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 9 May 2015 00:01:09 +0800 Subject: [PATCH 132/195] add trie impl --- implement-trie-prefix-tree/README.md | 0 implement-trie-prefix-tree/Solution.java | 91 ++++++++++++++++++++++++ implement-trie-prefix-tree/Trie.java | 1 + implement-trie-prefix-tree/index.md | 7 ++ 4 files changed, 99 insertions(+) create mode 100644 implement-trie-prefix-tree/README.md create mode 100644 implement-trie-prefix-tree/Solution.java create mode 120000 implement-trie-prefix-tree/Trie.java create mode 100644 implement-trie-prefix-tree/index.md diff --git a/implement-trie-prefix-tree/README.md b/implement-trie-prefix-tree/README.md new file mode 100644 index 0000000..e69de29 diff --git a/implement-trie-prefix-tree/Solution.java b/implement-trie-prefix-tree/Solution.java new file mode 100644 index 0000000..ed93530 --- /dev/null +++ b/implement-trie-prefix-tree/Solution.java @@ -0,0 +1,91 @@ +class TrieNode { + // Initialize your data structure here. + + TrieNode[] children = new TrieNode[26]; + + int count = 0; + + public TrieNode() { + + } + + TrieNode safe(int i){ + if(children[i] == null){ + children[i] = new TrieNode(); + } + + return children[i]; + } + + int index(char c){ + return (int)(c - 'a'); + } + + void insert(char[] word, int st, int len){ + if(len == 0){ + this.count++; + return; + } + + TrieNode t = safe(index(word[st])); + + t.insert(word, st + 1, len - 1); + } + + boolean search(char[] word, int st, int len){ + if(len == 0){ + return this.count > 0; + } + + TrieNode t = children[index(word[st])]; + + if(t == null){ + return false; + } + + return t.search(word, st + 1, len - 1); + } + + boolean startsWith(char[] prefix, int st, int len) { + if(len == 0){ + return true; + } + + TrieNode t = children[index(prefix[st])]; + + if(t == null){ + return false; + } + + return t.startsWith(prefix, st + 1, len - 1); + } +} + +public class Trie { + private TrieNode root; + + public Trie() { + root = new TrieNode(); + } + + // Inserts a word into the trie. + public void insert(String word) { + root.insert(word.toCharArray(), 0, word.length()); + } + + // Returns if the word is in the trie. + public boolean search(String word) { + return root.search(word.toCharArray(), 0, word.length()); + } + + // Returns if there is any word in the trie + // that starts with the given prefix. + public boolean startsWith(String prefix) { + return root.startsWith(prefix.toCharArray(), 0, prefix.length()); + } +} + +// Your Trie object will be instantiated and called as such: +// Trie trie = new Trie(); +// trie.insert("somestring"); +// trie.search("key"); diff --git a/implement-trie-prefix-tree/Trie.java b/implement-trie-prefix-tree/Trie.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/implement-trie-prefix-tree/Trie.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/implement-trie-prefix-tree/index.md b/implement-trie-prefix-tree/index.md new file mode 100644 index 0000000..6638f3a --- /dev/null +++ b/implement-trie-prefix-tree/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Implement Trie (Prefix Tree) +date: 2015-05-08 23:58:40+08:00 +leetcode_id: 208 +--- +{% include_relative README.md %} From 681bda30eab603e0305ff5453c62f41647b30615 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 9 May 2015 02:43:34 +0800 Subject: [PATCH 133/195] refine the code --- reverse-nodes-in-k-group/Solution.java | 70 +++++++++++++------------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/reverse-nodes-in-k-group/Solution.java b/reverse-nodes-in-k-group/Solution.java index 739b608..99bdc69 100644 --- a/reverse-nodes-in-k-group/Solution.java +++ b/reverse-nodes-in-k-group/Solution.java @@ -3,55 +3,53 @@ * public class ListNode { * int val; * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } + * ListNode(int x) { val = x; } * } */ public class Solution { + + ListNode reverse(ListNode head) { + + ListNode prev = null; + + while(head != null){ + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + public ListNode reverseKGroup(ListNode head, int k) { - // IMPORTANT: Please reset any member data you declared, as - // the same Solution instance will be reused for each test case. if(k <= 1) return head; - if(head == null) return null; if(head.next == null) return head; ListNode tail = head; - ListNode prev = null; - for(int i = 0; i < k ; i++){ - if(head == null){ - - // rollback - head = prev; - prev = null; - - while(head != null){ - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; - } - - return prev; - } - - ListNode t = head.next; - - head.next = prev; - prev = head; - - head = t; + for(int i = 1; i < k && tail != null; i++){ + tail = tail.next; } - tail.next = reverseKGroup(head, k); + if (tail == null) { + // less than k nodes + return head; + } - return prev; + ListNode next = tail.next; + tail.next = null; // cut + + tail = head; // head will be new tail + head = reverse(head); + + tail.next = reverseKGroup(next, k); + + return head; } -} \ No newline at end of file +} From 14dba2d874a2671fc0e99d61d258a1c821b06ee9 Mon Sep 17 00:00:00 2001 From: tgic Date: Sat, 9 May 2015 22:51:01 +0800 Subject: [PATCH 134/195] renew code --- powx-n/Solution.java | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/powx-n/Solution.java b/powx-n/Solution.java index f8e8026..d70d1b2 100644 --- a/powx-n/Solution.java +++ b/powx-n/Solution.java @@ -1,17 +1,14 @@ public class Solution { - public double pow(double x, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. - if(n == 0) return 1; + public double myPow(double x, int n) { - double s = pow(x, n /2); + if(n == 0) return 1; - if(n % 2 == 0) - return s * s; - else if(n > 0) - return s * s * x; - else - return s * s / x; + double s = myPow(x, n / 2); + if(n % 2 == 0) return s * s; + if(n > 0) return s * s * x; + // else n < 0 + return s * s / x; } } From 3ff8cfc5929341e8f4dd063ef337b5ab286f3409 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 10 May 2015 00:33:24 +0800 Subject: [PATCH 135/195] refine the code --- rotate-list/Solution.java | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/rotate-list/Solution.java b/rotate-list/Solution.java index efb2005..e978209 100644 --- a/rotate-list/Solution.java +++ b/rotate-list/Solution.java @@ -3,39 +3,36 @@ * public class ListNode { * int val; * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } + * ListNode(int x) { val = x; } * } */ public class Solution { - public ListNode rotateRight(ListNode head, int n) { - // Note: The Solution object is instantiated only once and is reused by each test case. + public ListNode rotateRight(ListNode head, int k) { if(head == null) return null; - ListNode _head = head; - - ListNode node = head; int len = 1; - while(node.next != null){ + + ListNode tail = head; + + while(tail.next != null){ len++; - node = node.next; + tail = tail.next; } - n %= len; - - ListNode tail = node; + tail.next = head; // cycle - node = head; - for(int i = 0; i < len - n - 1; i++) node = node.next; + k %= len; - tail.next = head; - ListNode rt = node.next; - node.next = null; + for(int i = 1; i < len - k; i++){ + head = head.next; + } - return rt; + try { + return head.next; + } finally { + head.next = null; // cut + } } -} \ No newline at end of file +} From 1209644117980a66fea154a0b26a6f38665d4329 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 10 May 2015 01:38:41 +0800 Subject: [PATCH 136/195] make jekyll happy --- scramble-string/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scramble-string/README.md b/scramble-string/README.md index 8a42161..e7fe5bc 100644 --- a/scramble-string/README.md +++ b/scramble-string/README.md @@ -54,6 +54,8 @@ that means we can make a filter to remove all `set` must not take `0` as its fir and `1` as it second and so on... so we build a methd + + ``` check_has_char(pos, letter, two_part_set) set = pos -> left_set or right_set depends on the two_part_set pivot From c14e0e2ba19ee9e81bcdcdb39a4c82e0185dc9e5 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 10 May 2015 01:51:44 +0800 Subject: [PATCH 137/195] java8 string.join --- restore-ip-addresses/Solution.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/restore-ip-addresses/Solution.java b/restore-ip-addresses/Solution.java index 97f46f4..9c766c3 100644 --- a/restore-ip-addresses/Solution.java +++ b/restore-ip-addresses/Solution.java @@ -9,7 +9,7 @@ void findnum(String s, int p, int pstack){ if(pstack == 4){ if(p >= s.length()){ - String ip = "" + stack[0] + "." + stack[1] + "." + stack[2] + "." + stack[3]; + String ip = String.join(".", stack); collect.add(ip); } From a5807ba773a75b847945b7bc77cd2114e729dbef Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 10 May 2015 01:53:43 +0800 Subject: [PATCH 138/195] return list --- binary-tree-inorder-traversal/Solution.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/binary-tree-inorder-traversal/Solution.java b/binary-tree-inorder-traversal/Solution.java index 9a01a4a..43a875a 100644 --- a/binary-tree-inorder-traversal/Solution.java +++ b/binary-tree-inorder-traversal/Solution.java @@ -22,10 +22,10 @@ static class StackState { } } - public ArrayList inorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); + public List inorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList<>(); - Deque stack = new LinkedList(); + Deque stack = new LinkedList<>(); if(root != null) stack.push(new StackState(root)); From d957a2a380ee2af8d653f0bd97ef8503c8b288cb Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 00:01:22 +0800 Subject: [PATCH 139/195] use java8 string.join --- word-break-ii/Solution.java | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/word-break-ii/Solution.java b/word-break-ii/Solution.java index 11df5fe..8873f6e 100644 --- a/word-break-ii/Solution.java +++ b/word-break-ii/Solution.java @@ -1,18 +1,5 @@ public class Solution { - String join(List list){ - if(list.isEmpty()) return ""; - - StringBuilder s = new StringBuilder(list.get(0)); - - for(int i = 1; i < list.size(); i++){ - s.append(' '); - s.append(list.get(i)); - } - - return s.toString(); - } - ArrayList[] P; char[] S; ArrayList rt; @@ -21,7 +8,7 @@ void joinAll(int offset, LinkedList parents){ if(P[offset].isEmpty()){ - rt.add(join(parents)); + rt.add(String.join(" ", parents)); return; } From 52c1e7c49e6b878c3076dbaeb778807e9fda1756 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 00:06:56 +0800 Subject: [PATCH 140/195] use list --- binary-tree-preorder-traversal/Solution.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/binary-tree-preorder-traversal/Solution.java b/binary-tree-preorder-traversal/Solution.java index 6172150..80f812d 100644 --- a/binary-tree-preorder-traversal/Solution.java +++ b/binary-tree-preorder-traversal/Solution.java @@ -22,11 +22,11 @@ static class StackState { } } - public ArrayList preorderTraversal(TreeNode root) { + public List preorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); + ArrayList rt = new ArrayList<>(); - Deque stack = new LinkedList(); + Deque stack = new LinkedList<>(); if(root != null) stack.push(new StackState(root)); From 4df0ba5d442ccc50d71f58a51d4b8e40cc5e9332 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 00:07:43 +0800 Subject: [PATCH 141/195] use list --- binary-tree-postorder-traversal/Solution.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/binary-tree-postorder-traversal/Solution.java b/binary-tree-postorder-traversal/Solution.java index 989a06e..d91e9f6 100644 --- a/binary-tree-postorder-traversal/Solution.java +++ b/binary-tree-postorder-traversal/Solution.java @@ -22,10 +22,10 @@ static class StackState { } } - public ArrayList postorderTraversal(TreeNode root) { - ArrayList rt = new ArrayList(); + public List postorderTraversal(TreeNode root) { + ArrayList rt = new ArrayList<>(); - Deque stack = new LinkedList(); + Deque stack = new LinkedList<>(); if(root != null) stack.push(new StackState(root)); From f88b1f07ded758cfb7459120a43575e20dad1169 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 00:19:55 +0800 Subject: [PATCH 142/195] upsideDownBinaryTree (was UpsideDownBinaryTree) --- binary-tree-upside-down/Solution.java | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/binary-tree-upside-down/Solution.java b/binary-tree-upside-down/Solution.java index 8632e7b..5a88db9 100644 --- a/binary-tree-upside-down/Solution.java +++ b/binary-tree-upside-down/Solution.java @@ -8,9 +8,9 @@ * } */ public class Solution { - - LinkedList queue = new LinkedList(); - + + LinkedList queue = new LinkedList<>(); + void inOrder(TreeNode root){ if(root == null) return; @@ -24,25 +24,26 @@ void inOrder(TreeNode root){ } + // bad side effect root.left = null; root.right = null; } - - public TreeNode UpsideDownBinaryTree(TreeNode root) { - + + public TreeNode upsideDownBinaryTree(TreeNode root) { + inOrder(root); - + TreeNode newRoot = queue.poll(); - + root = newRoot; - + while(!queue.isEmpty()){ root.right = queue.poll(); root.left = queue.poll(); root = root.right; } - + return newRoot; } } From cdf978d490f9b850fee719672bde7d61453fb92e Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 01:12:33 +0800 Subject: [PATCH 143/195] optimize code --- bitwise-and-of-numbers-range/Solution.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/bitwise-and-of-numbers-range/Solution.java b/bitwise-and-of-numbers-range/Solution.java index f0d8d81..db32634 100644 --- a/bitwise-and-of-numbers-range/Solution.java +++ b/bitwise-and-of-numbers-range/Solution.java @@ -1,12 +1,16 @@ public class Solution { - public int rangeBitwiseAnd(int m, int n) { - final int SIZE = Integer.SIZE; + + static final int SIZE = Integer.SIZE; - long[] POW = new long[SIZE + 1]; + static final long[] POW = new long[SIZE + 1]; + static { for(int i = 0; i < SIZE; i++){ POW[i] = (long)Math.pow(2, i); - } + } + } + + public int rangeBitwiseAnd(int m, int n) { for(int i = SIZE; i > 0; i--){ if(POW[i - 1] <= m && m < POW[i]){ From e2ee4b926430fec64925aca292e8af833af8c0b8 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 11 May 2015 01:15:34 +0800 Subject: [PATCH 144/195] update time --- binary-tree-inorder-traversal/index.md | 2 +- binary-tree-postorder-traversal/index.md | 2 +- binary-tree-preorder-traversal/index.md | 2 +- binary-tree-right-side-view/index.md | 2 +- binary-tree-upside-down/index.md | 2 +- bitwise-and-of-numbers-range/index.md | 2 +- count-primes/index.md | 2 +- course-schedule/index.md | 2 +- happy-number/index.md | 2 +- implement-trie-prefix-tree/index.md | 2 +- isomorphic-strings/index.md | 2 +- number-of-islands/index.md | 2 +- powx-n/index.md | 2 +- remove-linked-list-elements/index.md | 2 +- reorder-list/index.md | 2 +- restore-ip-addresses/index.md | 2 +- reverse-linked-list/index.md | 2 +- reverse-nodes-in-k-group/index.md | 2 +- rotate-list/index.md | 2 +- scramble-string/index.md | 2 +- word-break-ii/index.md | 2 +- 21 files changed, 21 insertions(+), 21 deletions(-) diff --git a/binary-tree-inorder-traversal/index.md b/binary-tree-inorder-traversal/index.md index 35dfbb1..7e71490 100644 --- a/binary-tree-inorder-traversal/index.md +++ b/binary-tree-inorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Inorder Traversal -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-10 01:53:43 +0800 leetcode_id: 94 --- {% include_relative README.md %} diff --git a/binary-tree-postorder-traversal/index.md b/binary-tree-postorder-traversal/index.md index 3492494..5029919 100644 --- a/binary-tree-postorder-traversal/index.md +++ b/binary-tree-postorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Postorder Traversal -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-11 00:07:43 +0800 leetcode_id: 145 --- {% include_relative README.md %} diff --git a/binary-tree-preorder-traversal/index.md b/binary-tree-preorder-traversal/index.md index c423e45..1e894dc 100644 --- a/binary-tree-preorder-traversal/index.md +++ b/binary-tree-preorder-traversal/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Preorder Traversal -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-11 00:06:56 +0800 leetcode_id: 144 --- {% include_relative README.md %} diff --git a/binary-tree-right-side-view/index.md b/binary-tree-right-side-view/index.md index e558487..e4990cd 100644 --- a/binary-tree-right-side-view/index.md +++ b/binary-tree-right-side-view/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Right Side View -date: 2015-04-03 21:32:41 +0800 +date: 2015-04-03 21:37:44 +0800 leetcode_id: 199 --- {% include_relative README.md %} diff --git a/binary-tree-upside-down/index.md b/binary-tree-upside-down/index.md index 1cea6ff..5ca357f 100644 --- a/binary-tree-upside-down/index.md +++ b/binary-tree-upside-down/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Binary Tree Upside Down -date: 2014-11-18 01:45:13 +0800 +date: 2015-05-11 00:19:55 +0800 leetcode_id: 156 --- {% include_relative README.md %} diff --git a/bitwise-and-of-numbers-range/index.md b/bitwise-and-of-numbers-range/index.md index 0041852..03138a9 100644 --- a/bitwise-and-of-numbers-range/index.md +++ b/bitwise-and-of-numbers-range/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Bitwise AND of Numbers Range -date: 2015-04-21 01:17:47+08:00 +date: 2015-05-11 01:12:33 +0800 leetcode_id: 201 --- {% include_relative README.md %} diff --git a/count-primes/index.md b/count-primes/index.md index 8feafa0..4e43bb4 100644 --- a/count-primes/index.md +++ b/count-primes/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Count Primes -date: 2015-04-27 16:39:19+08:00 +date: 2015-04-27 16:40:41 +0800 leetcode_id: 204 --- {% include_relative README.md %} diff --git a/course-schedule/index.md b/course-schedule/index.md index 6c4da2d..c5a98c1 100644 --- a/course-schedule/index.md +++ b/course-schedule/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Course Schedule -date: 2015-05-07 00:48:21+08:00 +date: 2015-05-07 00:51:31 +0800 leetcode_id: 207 --- {% include_relative README.md %} diff --git a/happy-number/index.md b/happy-number/index.md index 3053af5..a5d1230 100644 --- a/happy-number/index.md +++ b/happy-number/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Happy Number -date: 2015-04-22 12:33:21+08:00 +date: 2015-04-22 12:34:48 +0800 leetcode_id: 202 --- {% include_relative README.md %} diff --git a/implement-trie-prefix-tree/index.md b/implement-trie-prefix-tree/index.md index 6638f3a..d0a19ec 100644 --- a/implement-trie-prefix-tree/index.md +++ b/implement-trie-prefix-tree/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Implement Trie (Prefix Tree) -date: 2015-05-08 23:58:40+08:00 +date: 2015-05-09 00:01:09 +0800 leetcode_id: 208 --- {% include_relative README.md %} diff --git a/isomorphic-strings/index.md b/isomorphic-strings/index.md index a04ce3e..d5aa475 100644 --- a/isomorphic-strings/index.md +++ b/isomorphic-strings/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Isomorphic Strings -date: 2015-04-29 12:07:38+08:00 +date: 2015-04-29 12:09:06 +0800 leetcode_id: 205 --- {% include_relative README.md %} diff --git a/number-of-islands/index.md b/number-of-islands/index.md index 5d3dc64..7c4093a 100644 --- a/number-of-islands/index.md +++ b/number-of-islands/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Number of Islands -date: 2015-04-08 13:28:15+08:00 +date: 2015-04-08 15:07:58 +0800 leetcode_id: 200 --- {% include_relative README.md %} diff --git a/powx-n/index.md b/powx-n/index.md index d0f44ed..efe0fd2 100644 --- a/powx-n/index.md +++ b/powx-n/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Pow(x, n) -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-09 22:51:01 +0800 leetcode_id: 50 --- {% include_relative README.md %} diff --git a/remove-linked-list-elements/index.md b/remove-linked-list-elements/index.md index 421610a..b594a2f 100644 --- a/remove-linked-list-elements/index.md +++ b/remove-linked-list-elements/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Remove Linked List Elements -date: 2015-04-23 11:38:34+08:00 +date: 2015-04-23 11:39:56 +0800 leetcode_id: 203 --- {% include_relative README.md %} diff --git a/reorder-list/index.md b/reorder-list/index.md index e339b43..9128272 100644 --- a/reorder-list/index.md +++ b/reorder-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reorder List -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-05 11:59:41 +0800 leetcode_id: 143 --- {% include_relative README.md %} diff --git a/restore-ip-addresses/index.md b/restore-ip-addresses/index.md index 99e6e2b..b5fb755 100644 --- a/restore-ip-addresses/index.md +++ b/restore-ip-addresses/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Restore IP Addresses -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-10 01:51:44 +0800 leetcode_id: 93 --- {% include_relative README.md %} diff --git a/reverse-linked-list/index.md b/reverse-linked-list/index.md index eead8fb..865563e 100644 --- a/reverse-linked-list/index.md +++ b/reverse-linked-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Linked List -date: 2015-05-05 11:37:08+08:00 +date: 2015-05-05 11:48:40 +0800 leetcode_id: 206 --- {% include_relative README.md %} diff --git a/reverse-nodes-in-k-group/index.md b/reverse-nodes-in-k-group/index.md index 5c1be88..d7e686d 100644 --- a/reverse-nodes-in-k-group/index.md +++ b/reverse-nodes-in-k-group/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Reverse Nodes in k-Group -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-09 02:43:34 +0800 leetcode_id: 25 --- {% include_relative README.md %} diff --git a/rotate-list/index.md b/rotate-list/index.md index 7998645..c9539f8 100644 --- a/rotate-list/index.md +++ b/rotate-list/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Rotate List -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-10 00:33:24 +0800 leetcode_id: 61 --- {% include_relative README.md %} diff --git a/scramble-string/index.md b/scramble-string/index.md index 7744138..d377ad4 100644 --- a/scramble-string/index.md +++ b/scramble-string/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Scramble String -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-10 01:38:41 +0800 leetcode_id: 87 --- {% include_relative README.md %} diff --git a/word-break-ii/index.md b/word-break-ii/index.md index 31eeab9..6bc758c 100644 --- a/word-break-ii/index.md +++ b/word-break-ii/index.md @@ -1,7 +1,7 @@ --- layout: solution title: Word Break II -date: 2014-12-29 00:26:24 +0800 +date: 2015-05-11 00:01:22 +0800 leetcode_id: 140 --- {% include_relative README.md %} From 262c8af3e52f0b400e67bb9d1cf00b622064950e Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 12 May 2015 14:46:53 +0800 Subject: [PATCH 145/195] add min size subarray --- minimum-size-subarray-sum/README.md | 0 minimum-size-subarray-sum/Solution.java | 30 +++++++++++++++++++++++++ minimum-size-subarray-sum/index.md | 7 ++++++ 3 files changed, 37 insertions(+) create mode 100644 minimum-size-subarray-sum/README.md create mode 100644 minimum-size-subarray-sum/Solution.java create mode 100644 minimum-size-subarray-sum/index.md diff --git a/minimum-size-subarray-sum/README.md b/minimum-size-subarray-sum/README.md new file mode 100644 index 0000000..e69de29 diff --git a/minimum-size-subarray-sum/Solution.java b/minimum-size-subarray-sum/Solution.java new file mode 100644 index 0000000..a291a9e --- /dev/null +++ b/minimum-size-subarray-sum/Solution.java @@ -0,0 +1,30 @@ +public class Solution { + public int minSubArrayLen(int s, int[] nums) { + + int sum = 0; + + int st = 0; + + int c = nums.length + 1; + + for (int i = 0; i < nums.length; i++) { + + sum += nums[i]; + + if(sum >= s){ + while(sum - nums[st] >= s) { + sum -= nums[st++]; + } + + c = Math.min(c, i - st + 1); + } + + } + + if(c > nums.length) { + return 0; + } + + return c; + } +} diff --git a/minimum-size-subarray-sum/index.md b/minimum-size-subarray-sum/index.md new file mode 100644 index 0000000..feff633 --- /dev/null +++ b/minimum-size-subarray-sum/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Minimum Size Subarray Sum +date: 2015-05-12 14:45:40+08:00 +leetcode_id: 209 +--- +{% include_relative README.md %} From b53d582f610db62164abae0bb73e16e48518bbdf Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 14 May 2015 00:33:04 +0800 Subject: [PATCH 146/195] course shed ii --- course-schedule-ii/README.md | 0 course-schedule-ii/Solution.java | 69 ++++++++++++++++++++++++++++++++ course-schedule-ii/index.md | 7 ++++ 3 files changed, 76 insertions(+) create mode 100644 course-schedule-ii/README.md create mode 100644 course-schedule-ii/Solution.java create mode 100644 course-schedule-ii/index.md diff --git a/course-schedule-ii/README.md b/course-schedule-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/course-schedule-ii/Solution.java b/course-schedule-ii/Solution.java new file mode 100644 index 0000000..895f837 --- /dev/null +++ b/course-schedule-ii/Solution.java @@ -0,0 +1,69 @@ +public class Solution { + + static class Vertex { + + int id; + + Vertex(int id){ + this.id = id; + } + + Set in = new HashSet<>(); + Set out = new HashSet<>(); + + boolean isSink(){ + return out.isEmpty(); + } + } + + Vertex safe(Vertex[] G, int id){ + if(G[id] == null){ + G[id] = new Vertex(id); + } + + return G[id]; + } + + public int[] findOrder(int numCourses, int[][] prerequisites) { + Vertex[] G = new Vertex[numCourses]; + + for(int[] p : prerequisites){ + safe(G, p[0]).out.add(p[1]); + safe(G, p[1]).in.add(p[0]); + } + + Set S = Arrays.stream(G) + .filter(v -> v != null) + .collect(Collectors.toSet()); + + + LinkedHashSet order = new LinkedHashSet<>(numCourses); + + loop: + while(!S.isEmpty()){ + + for(Vertex v : S){ + if(v.isSink()){ + order.add(v.id); + + S.remove(v); + + for(int i : v.in){ + G[i].out.remove(v.id); + } + + continue loop; + } + } + + return new int[]{}; + } + + // fill courses not in G + order.addAll(IntStream.range(0, numCourses).boxed().collect(Collectors.toSet())); + + return order.stream() + .mapToInt(i -> i) + .toArray(); + } +} diff --git a/course-schedule-ii/index.md b/course-schedule-ii/index.md new file mode 100644 index 0000000..cb84cb8 --- /dev/null +++ b/course-schedule-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Course Schedule II +date: 2015-05-14 00:31:26+08:00 +leetcode_id: 210 +--- +{% include_relative README.md %} From 5b323f1c187d41e9b1ffe05fcf83171ea33fcf8f Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 18 May 2015 22:27:21 +0800 Subject: [PATCH 147/195] add trie tree ii --- .../README.md | 0 .../Solution.java | 82 +++++++++++++++++++ .../WordDictionary.java | 1 + .../index.md | 7 ++ 4 files changed, 90 insertions(+) create mode 100644 add-and-search-word-data-structure-design/README.md create mode 100644 add-and-search-word-data-structure-design/Solution.java create mode 120000 add-and-search-word-data-structure-design/WordDictionary.java create mode 100644 add-and-search-word-data-structure-design/index.md diff --git a/add-and-search-word-data-structure-design/README.md b/add-and-search-word-data-structure-design/README.md new file mode 100644 index 0000000..e69de29 diff --git a/add-and-search-word-data-structure-design/Solution.java b/add-and-search-word-data-structure-design/Solution.java new file mode 100644 index 0000000..51dda42 --- /dev/null +++ b/add-and-search-word-data-structure-design/Solution.java @@ -0,0 +1,82 @@ +public class WordDictionary { + + static class TrieNode { + // Initialize your data structure here. + + TrieNode[] children = new TrieNode[26]; + + int count = 0; + + public TrieNode() { + + } + + TrieNode safe(int i){ + if(children[i] == null){ + children[i] = new TrieNode(); + } + + return children[i]; + } + + int index(char c){ + return (int)(c - 'a'); + } + + void insert(char[] word, int st, int len){ + if(len == 0){ + this.count++; + return; + } + + TrieNode t = safe(index(word[st])); + + t.insert(word, st + 1, len - 1); + } + + boolean search(char[] word, int st, int len){ + if(len == 0){ + return this.count > 0; + } + + if(word[st] == '.'){ + + for(TrieNode t : children){ + if(t != null){ + if(t.search(word, st + 1, len - 1)){ + return true; + } + } + } + + return false; + } + + TrieNode t = children[index(word[st])]; + + if(t == null){ + return false; + } + + return t.search(word, st + 1, len - 1); + } + } + + TrieNode root = new TrieNode(); + + // Adds a word into the data structure. + public void addWord(String word) { + root.insert(word.toCharArray(), 0, word.length()); + } + + // Returns if the word is in the data structure. A word could + // contain the dot character '.' to represent any one letter. + public boolean search(String word) { + return root.search(word.toCharArray(), 0, word.length()); + } +} + +// Your WordDictionary object will be instantiated and called as such: +// WordDictionary wordDictionary = new WordDictionary(); +// wordDictionary.addWord("word"); +// wordDictionary.search("pattern"); diff --git a/add-and-search-word-data-structure-design/WordDictionary.java b/add-and-search-word-data-structure-design/WordDictionary.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/add-and-search-word-data-structure-design/WordDictionary.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/add-and-search-word-data-structure-design/index.md b/add-and-search-word-data-structure-design/index.md new file mode 100644 index 0000000..2cd5b99 --- /dev/null +++ b/add-and-search-word-data-structure-design/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Add and Search Word - Data structure design +date: 2015-05-18 22:25:43+08:00 +leetcode_id: 211 +--- +{% include_relative README.md %} From 525d890f517d58361197ec48f2e5aa7a42c8a51d Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 18 May 2015 22:33:14 +0800 Subject: [PATCH 148/195] new leetcode url pattern (was oj.leetcode.com/) --- _layouts/solution.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_layouts/solution.html b/_layouts/solution.html index dc81d53..ab32238 100644 --- a/_layouts/solution.html +++ b/_layouts/solution.html @@ -2,7 +2,7 @@ layout: default --- {% assign leetcode_name = {{page.path | remove: '/index.md'}} %} -{% assign leetcode_url = {{leetcode_name | prepend: 'https://oj.leetcode.com/problems/'}} %} +{% assign leetcode_url = {{leetcode_name | prepend: 'https://leetcode.com/problems/'}} %} {% assign github_url = {{leetcode_name | prepend: 'https://github.com/tg123/leetcode/blob/gh-pages/' }} %} {% assign github_source_url = {{leetcode_name | prepend: 'https://github.com/tg123/leetcode/blob/gh-pages/' | append: '/Solution.java' }} %} From f4e964a063d29e189d3fee28aff53559ed1fec5f Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 20 May 2015 00:35:07 +0800 Subject: [PATCH 149/195] add word search ii --- word-search-ii/README.md | 0 word-search-ii/Solution.java | 141 +++++++++++++++++++++++++++++++++++ word-search-ii/index.md | 7 ++ 3 files changed, 148 insertions(+) create mode 100644 word-search-ii/README.md create mode 100644 word-search-ii/Solution.java create mode 100644 word-search-ii/index.md diff --git a/word-search-ii/README.md b/word-search-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/word-search-ii/Solution.java b/word-search-ii/Solution.java new file mode 100644 index 0000000..1107f8b --- /dev/null +++ b/word-search-ii/Solution.java @@ -0,0 +1,141 @@ +public class Solution { + + static class TrieNode { + // Initialize your data structure here. + TrieNode parent; + int depth = 0; + + char character; + + TrieNode[] children = new TrieNode[26]; + + int count = 0; + + public TrieNode(TrieNode parent, char character) { + this.parent = parent; + this.character = character; + + if(parent != null) { + this.depth = parent.depth + 1; + } + } + + TrieNode safe(char c){ + int i = index(c); + + if(children[i] == null){ + children[i] = new TrieNode(this, c); + } + + return children[i]; + } + + int index(char c){ + return (int)(c - 'a'); + } + + void insert(char[] word, int st, int len){ + if(len == 0){ + this.count++; + return; + } + + TrieNode t = safe(word[st]); + + t.insert(word, st + 1, len - 1); + } + + TrieNode child(char c){ + return children[index(c)]; + } + + boolean hasChild(char c){ + return child(c) != null; + } + + String recover(){ + // assert count > 0 + TrieNode t = this; + char[] s = new char[depth]; + + for(int i = depth - 1; i >= 0; i--){ + s[i] = t.character; + t = t.parent; + } + + return new String(s); + } + } + + int flatten(int x, int y, int wide){ + return x * wide + y; + } + + boolean vaild(int x, int y, char[][] board){ + return x >= 0 && + y >= 0 && + x < board.length && + y < board[0].length; + } + + Set found = new HashSet<>(); + + void findWords(int x, int y, char[][] board, boolean[] vi, TrieNode current) { + + vi[flatten(x, y, board[0].length)] = true; + + if(current.count > 0){ + found.add(current.recover()); + } + + for(int[] xy : new int[][] { + {x + 1, y}, + {x, y + 1}, + {x - 1, y}, + {x, y - 1}, + }) { + int _x = xy[0]; + int _y = xy[1]; + + if(!vaild(_x, _y, board)){ + continue; + } + + if(vi[flatten(_x, _y, board[0].length)]) { + continue; + } + + TrieNode t = current.child(board[_x][_y]); + + if(t == null){ + continue; + } + + findWords(_x, _y, board, vi, t); + + vi[flatten(_x, _y, board[0].length)] = false; + } + + } + + public List findWords(char[][] board, String[] words) { + + TrieNode root = new TrieNode(null, '\0'); + + for(String w : words){ + root.insert(w.toCharArray(), 0, w.length()); + } + + final int LEN = board.length * board[0].length; + + for(int x = 0; x < board.length; x++){ + for(int y = 0; y < board[0].length; y++){ + if(root.hasChild(board[x][y])){ + findWords(x, y, board, new boolean[LEN], root.child(board[x][y])); + } + } + } + + return new ArrayList<>(found); + } +} diff --git a/word-search-ii/index.md b/word-search-ii/index.md new file mode 100644 index 0000000..2274fed --- /dev/null +++ b/word-search-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Word Search II +date: 2015-05-20 00:32:45+08:00 +leetcode_id: 212 +--- +{% include_relative README.md %} From 80852644adee7b53b085a4b1110176c00d681c83 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 20 May 2015 11:53:41 +0800 Subject: [PATCH 150/195] add horse rob ii --- house-robber-ii/README.md | 0 house-robber-ii/Solution.java | 27 +++++++++++++++++++++++++++ house-robber-ii/index.md | 7 +++++++ 3 files changed, 34 insertions(+) create mode 100644 house-robber-ii/README.md create mode 100644 house-robber-ii/Solution.java create mode 100644 house-robber-ii/index.md diff --git a/house-robber-ii/README.md b/house-robber-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/house-robber-ii/Solution.java b/house-robber-ii/Solution.java new file mode 100644 index 0000000..664af93 --- /dev/null +++ b/house-robber-ii/Solution.java @@ -0,0 +1,27 @@ +public class Solution { + + // rob1 + int rob(int[] num, int st, int len) { + if(len == 0) return 0; + if(len == 1) return num[st + 0]; + + int[] P = new int[len]; + + P[0] = num[st + 0]; + P[1] = Math.max(num[st + 0], num[st + 1]); + + for(int i = 2; i < len; i++){ + P[i] = Math.max(num[st + i] + P[i - 2], P[i - 1]); + } + + return P[len - 1]; + } + + public int rob(int[] nums) { + + if(nums.length == 0) return 0; + if(nums.length == 1) return nums[0]; + + return Math.max(rob(nums, 0, nums.length - 1), rob(nums, 1, nums.length - 1)); + } +} diff --git a/house-robber-ii/index.md b/house-robber-ii/index.md new file mode 100644 index 0000000..af9e2f7 --- /dev/null +++ b/house-robber-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: House Robber II +date: 2015-05-20 11:52:10+08:00 +leetcode_id: 213 +--- +{% include_relative README.md %} From 8345ac876208aa80bd36b1ca8c9a15b7d7bf3b84 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 20 May 2015 11:55:58 +0800 Subject: [PATCH 151/195] fix typo --- house-robber/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/house-robber/README.md b/house-robber/README.md index 2ebe8c4..c694a4d 100644 --- a/house-robber/README.md +++ b/house-robber/README.md @@ -1,7 +1,7 @@ ## Rob or not assume that there are 9 houses along the street -and you have a `rob` func can tell you the how much money you can get from first 8 hourses. +and you have a `rob` func can tell you the how much money you can get from first 8 houses. what about the 9th house From 74e5dc20477861f67e24eb61b235bd2b3d6cf8e2 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 25 May 2015 23:35:09 +0800 Subject: [PATCH 152/195] add contain dup --- contains-duplicate/README.md | 0 contains-duplicate/Solution.java | 15 +++++++++++++++ contains-duplicate/index.md | 7 +++++++ 3 files changed, 22 insertions(+) create mode 100644 contains-duplicate/README.md create mode 100644 contains-duplicate/Solution.java create mode 100644 contains-duplicate/index.md diff --git a/contains-duplicate/README.md b/contains-duplicate/README.md new file mode 100644 index 0000000..e69de29 diff --git a/contains-duplicate/Solution.java b/contains-duplicate/Solution.java new file mode 100644 index 0000000..8a51256 --- /dev/null +++ b/contains-duplicate/Solution.java @@ -0,0 +1,15 @@ +public class Solution { + public boolean containsDuplicate(int[] nums) { + Set s = new HashSet<>(); + + for(int n : nums){ + if(s.contains(n)){ + return true; + } + + s.add(n); + } + + return false; + } +} diff --git a/contains-duplicate/index.md b/contains-duplicate/index.md new file mode 100644 index 0000000..f38ae53 --- /dev/null +++ b/contains-duplicate/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Contains Duplicate +date: 2015-05-25 19:40:06+08:00 +leetcode_id: 217 +--- +{% include_relative README.md %} From 2302fb83da594244db6c7f707222941b3ef4d0fa Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 26 May 2015 01:20:55 +0800 Subject: [PATCH 153/195] add shortest pal --- shortest-palindrome/README.md | 0 shortest-palindrome/Solution.java | 50 +++++++++++++++++++++++++++++++ shortest-palindrome/index.md | 7 +++++ 3 files changed, 57 insertions(+) create mode 100644 shortest-palindrome/README.md create mode 100644 shortest-palindrome/Solution.java create mode 100644 shortest-palindrome/index.md diff --git a/shortest-palindrome/README.md b/shortest-palindrome/README.md new file mode 100644 index 0000000..e69de29 diff --git a/shortest-palindrome/Solution.java b/shortest-palindrome/Solution.java new file mode 100644 index 0000000..74f385a --- /dev/null +++ b/shortest-palindrome/Solution.java @@ -0,0 +1,50 @@ +public class Solution { + public String shortestPalindrome(String s) { + char[] S = s.toCharArray(); + + int[] P = new int[S.length]; + + for(int i = S.length - 2; i >= 0; i--){ + if(S[i] == S[i + 1]){ + P[i] = P[i + 1] + 1; + } + } + + int i = 0; + int e = S.length - 1; + + int j = e; + + while(i < j){ + + if(S[i] == S[j]){ + + i++; + j--; + + } else { + + if(P[j] >= i){ + j--; + e--; + + } else if(i > 0) { + + i = 0; + e = j; + + } else { + + j = e - 1; + e--; + } + } + } + + StringBuilder sb = new StringBuilder(new String(S, e + 1, S.length - e - 1)).reverse(); + + sb.append(s); + + return sb.toString(); + } +} diff --git a/shortest-palindrome/index.md b/shortest-palindrome/index.md new file mode 100644 index 0000000..aa04491 --- /dev/null +++ b/shortest-palindrome/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Shortest Palindrome +date: 2015-05-26 01:19:56+08:00 +leetcode_id: 214 +--- +{% include_relative README.md %} From e90d4f26e0f018d6143c0d04c879537339804750 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 26 May 2015 01:33:37 +0800 Subject: [PATCH 154/195] ... not clear with this problem --- kth-largest-element-in-an-array/README.md | 0 kth-largest-element-in-an-array/Solution.java | 7 +++++++ kth-largest-element-in-an-array/index.md | 7 +++++++ 3 files changed, 14 insertions(+) create mode 100644 kth-largest-element-in-an-array/README.md create mode 100644 kth-largest-element-in-an-array/Solution.java create mode 100644 kth-largest-element-in-an-array/index.md diff --git a/kth-largest-element-in-an-array/README.md b/kth-largest-element-in-an-array/README.md new file mode 100644 index 0000000..e69de29 diff --git a/kth-largest-element-in-an-array/Solution.java b/kth-largest-element-in-an-array/Solution.java new file mode 100644 index 0000000..5012f30 --- /dev/null +++ b/kth-largest-element-in-an-array/Solution.java @@ -0,0 +1,7 @@ +public class Solution { + public int findKthLargest(int[] nums, int k) { + Arrays.sort(nums); + + return nums[nums.length - k]; + } +} diff --git a/kth-largest-element-in-an-array/index.md b/kth-largest-element-in-an-array/index.md new file mode 100644 index 0000000..403edfb --- /dev/null +++ b/kth-largest-element-in-an-array/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Kth Largest Element in an Array +date: 2015-05-26 01:30:24+08:00 +leetcode_id: 215 +--- +{% include_relative README.md %} From 2ef5cf714fcadddd6e9d69ba852eb1689fa307e0 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 26 May 2015 02:06:39 +0800 Subject: [PATCH 155/195] add combination sum iii --- combination-sum-iii/README.md | 0 combination-sum-iii/Solution.java | 41 +++++++++++++++++++++++++++++++ combination-sum-iii/index.md | 7 ++++++ 3 files changed, 48 insertions(+) create mode 100644 combination-sum-iii/README.md create mode 100644 combination-sum-iii/Solution.java create mode 100644 combination-sum-iii/index.md diff --git a/combination-sum-iii/README.md b/combination-sum-iii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/combination-sum-iii/Solution.java b/combination-sum-iii/Solution.java new file mode 100644 index 0000000..e855819 --- /dev/null +++ b/combination-sum-iii/Solution.java @@ -0,0 +1,41 @@ +public class Solution { + + Integer[] stack; + List> found; + + void search(int p, int k, int current, int n, int st){ + + if(p == k){ + if(n == current){ + found.add(new ArrayList<>(Arrays.asList(stack))); + } + + return; + } + + // cut + if(current + 9 * (k - p) < n){ + return; + } + + if(current + 1 * (k - p) > n){ + return; + } + + for(int i = st; i < 10; i++){ + if(current + i <= n){ + stack[p] = i; + search(p + 1, k, current + i, n, i + 1); + } + } + } + + public List> combinationSum3(int k, int n) { + found = new ArrayList<>(); + stack = new Integer[k]; + + search(0, k, 0, n, 1); + + return found; + } +} diff --git a/combination-sum-iii/index.md b/combination-sum-iii/index.md new file mode 100644 index 0000000..fc4f38e --- /dev/null +++ b/combination-sum-iii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Combination Sum III +date: 2015-05-26 02:05:29+08:00 +leetcode_id: 216 +--- +{% include_relative README.md %} From 903217ecdf9a516d4ea908847aa0f2aa4dcb1dd9 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 28 May 2015 19:48:18 +0800 Subject: [PATCH 156/195] too hard take me 2 days: skyline --- the-skyline-problem/README.md | 0 the-skyline-problem/Solution.java | 124 ++++++++++++++++++++++++++++++ the-skyline-problem/index.md | 7 ++ 3 files changed, 131 insertions(+) create mode 100644 the-skyline-problem/README.md create mode 100644 the-skyline-problem/Solution.java create mode 100644 the-skyline-problem/index.md diff --git a/the-skyline-problem/README.md b/the-skyline-problem/README.md new file mode 100644 index 0000000..e69de29 diff --git a/the-skyline-problem/Solution.java b/the-skyline-problem/Solution.java new file mode 100644 index 0000000..ff2b372 --- /dev/null +++ b/the-skyline-problem/Solution.java @@ -0,0 +1,124 @@ +public class Solution { + static int li(int[] building){ + return building[0]; + } + + static int ri(int[] building){ + return building[1]; + } + + static int hi(int[] building){ + return building[2]; + } + + static class SortedBuilds { + int[][] buildings; + int p = 0; + + PriorityQueue inserted = new PriorityQueue<>((a, b) -> li(a) - li(b)); + + SortedBuilds(int[][] buildings) { + this.buildings = buildings; + } + + boolean hasNext(){ + return p < buildings.length || !inserted.isEmpty(); + } + + + int[] next(){ + + if(p < buildings.length && !inserted.isEmpty()){ + + if(li(buildings[p]) < li(inserted.peek())){ + return buildings[p++]; + }else{ + return inserted.poll(); + } + + } else if(p < buildings.length ){ + return buildings[p++]; + } else { // !inserted.isEmpty()) + return inserted.poll(); + } + + } + + void insert(int[] building){ + inserted.add(building); + } + } + + public List getSkyline(int[][] buildings) { + + List all = new ArrayList<>(); + if(buildings.length == 0) return all; + + SortedBuilds sortedBuilds = new SortedBuilds(buildings); + + int[] a = sortedBuilds.next(); + + while (sortedBuilds.hasNext()){ + int[] b = sortedBuilds.next(); + + if(ri(a) == li(b) && hi(a) == hi(b)){ + a = new int[]{li(a), ri(b), hi(a)}; + continue; + } + + // a.r b.l + if(ri(a) <= li(b)){ + all.add(new int[]{li(a), hi(a)}); + + if(ri(a) < li(b)){ + all.add(new int[]{ri(a), 0}); + } + + a = b; + continue; + } + + // a.l b.l + if(li(a) == li(b)){ + + // make a higher than b + if(hi(a) < hi(b)){ + sortedBuilds.insert(a); + a = b; + continue; + } + + if(ri(a) < ri(b)){ + sortedBuilds.insert(new int[]{ri(a), ri(b), hi(b)}); + } + // else drop b (b inside a) + continue; + } + + // + if(hi(a) < hi(b)){ + + all.add(new int[]{li(a), hi(a)}); + + if(ri(a) > ri(b)){ + sortedBuilds.insert(new int[]{ri(b), ri(a), hi(a)}); + } + + a = b; + continue; + } + + // a.h >= b.h + + if(ri(a) < ri(b)){ + sortedBuilds.insert(new int[]{ri(a), ri(b), hi(b)}); + } + // else drop b (b inside a) + } + + all.add(new int[]{li(a), hi(a)}); + all.add(new int[]{ri(a), 0}); + + return all; + } +} diff --git a/the-skyline-problem/index.md b/the-skyline-problem/index.md new file mode 100644 index 0000000..7e48923 --- /dev/null +++ b/the-skyline-problem/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: The Skyline Problem +date: 2015-05-28 19:45:44+08:00 +leetcode_id: 218 +--- +{% include_relative README.md %} From 6f5dd5f17e3122e3d6e8e0d6bf108cf1614e1a9a Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 29 May 2015 11:56:26 +0800 Subject: [PATCH 157/195] contains dup ii --- contains-duplicate-ii/README.md | 0 contains-duplicate-ii/Solution.java | 27 +++++++++++++++++++++++++++ contains-duplicate-ii/index.md | 7 +++++++ 3 files changed, 34 insertions(+) create mode 100644 contains-duplicate-ii/README.md create mode 100644 contains-duplicate-ii/Solution.java create mode 100644 contains-duplicate-ii/index.md diff --git a/contains-duplicate-ii/README.md b/contains-duplicate-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/contains-duplicate-ii/Solution.java b/contains-duplicate-ii/Solution.java new file mode 100644 index 0000000..00a613a --- /dev/null +++ b/contains-duplicate-ii/Solution.java @@ -0,0 +1,27 @@ +public class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + + if(k <= 0) return false; + + Map> pairs = new HashMap<>(); + + for(int i = 0; i < nums.length; i++){ + List l = pairs.get(nums[i]); + + if(l == null){ + l = new ArrayList<>(); + pairs.put(nums[i], l); + } else { + for(int j : l){ + if(i - j <= k){ + return true; + } + } + } + + l.add(i); + } + + return false; + } +} diff --git a/contains-duplicate-ii/index.md b/contains-duplicate-ii/index.md new file mode 100644 index 0000000..0abfdd1 --- /dev/null +++ b/contains-duplicate-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Contains Duplicate II +date: 2015-05-29 11:55:22+08:00 +leetcode_id: 219 +--- +{% include_relative README.md %} From 6a62a7d8a7cd3825621e8f9c2fad8c9493ec80d4 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 31 May 2015 01:01:13 +0800 Subject: [PATCH 158/195] a minheap version --- kth-largest-element-in-an-array/Solution.java | 82 ++++++++++++++++++- 1 file changed, 79 insertions(+), 3 deletions(-) diff --git a/kth-largest-element-in-an-array/Solution.java b/kth-largest-element-in-an-array/Solution.java index 5012f30..749278b 100644 --- a/kth-largest-element-in-an-array/Solution.java +++ b/kth-largest-element-in-an-array/Solution.java @@ -1,7 +1,83 @@ public class Solution { - public int findKthLargest(int[] nums, int k) { - Arrays.sort(nums); + + static class MinHeap { + + int[] data; + + int currentSize = 0; + + MinHeap(int size){ + data = new int[size]; + } + + int parent(int i){ + return (i - 1) / 2; + } + + int left(int i){ + return 2 * i + 1; + } + + int right(int i){ + return 2 * i + 2; + } - return nums[nums.length - k]; + void add(int n){ + int i = currentSize; + currentSize++; + + data[i] = n; + + while(i > 0 && data[parent(i)] > data[i]){ + swap(parent(i), i); + i = parent(i); + } + } + + void heapify(int i){ + + int l = left(i); + int r = right(i); + int min = i; + + if(l < currentSize && data[l] < data[min]){ + min = l; + } + + if(r < currentSize && data[r] < data[min]){ + min = r; + } + + if(min != i){ + swap(i, min); + heapify(min); + } + + } + + void swap(int x, int y){ + int t = data[x]; + data[x] = data[y]; + data[y] = t; + } + } + + public int findKthLargest(int[] nums, int k) { + + MinHeap heap = new MinHeap(k); + + for(int i = 0; i < Math.min(nums.length, k); i++){ + heap.add(nums[i]); + } + + for(int i = k; i < nums.length; i++){ + + if(heap.data[0] < nums[i]){ + heap.data[0] = nums[i]; + heap.heapify(0); + } + } + + return heap.data[0]; } } From b3c6f4f27dc123e0714859b0561152a5136adbee Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 2 Jun 2015 01:38:50 +0800 Subject: [PATCH 159/195] contain dup iii --- contains-duplicate-iii/README.md | 0 contains-duplicate-iii/Solution.java | 80 ++++++++++++++++++++++++++++ contains-duplicate-iii/index.md | 7 +++ 3 files changed, 87 insertions(+) create mode 100644 contains-duplicate-iii/README.md create mode 100644 contains-duplicate-iii/Solution.java create mode 100644 contains-duplicate-iii/index.md diff --git a/contains-duplicate-iii/README.md b/contains-duplicate-iii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/contains-duplicate-iii/Solution.java b/contains-duplicate-iii/Solution.java new file mode 100644 index 0000000..548af82 --- /dev/null +++ b/contains-duplicate-iii/Solution.java @@ -0,0 +1,80 @@ +public class Solution { + + static class Tree { + TreeMap tree = new TreeMap<>(); + + int size = 0; + + void add(Integer n){ + Integer v = tree.get(n); + + if(v == null){ + v = 0; + } + + tree.put(n, v + 1); + + size++; + } + + void remove(Integer n){ + Integer v = tree.get(n); + + v--; + + if(v == 0){ + tree.remove(n); + } else { + tree.put(n, v); + } + + size--; + } + + // fuck overflow + long nearSub(Integer n){ + + Integer v = tree.get(n); + if(v >= 2) return 0; + + long min = Long.MAX_VALUE; + + Integer h = tree.higherKey(n); + if(h != null){ + min = h - n; + } + + Integer l = tree.lowerKey(n); + if(l != null){ + min = Math.min(min, (long)n - l); + } + + return min; + } + } + + public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { + if (k <= 0) return false; + if (nums.length <= 1) return false; + + Tree tree = new Tree(); + + tree.add(nums[0]); + + int p = 0; + for(int i = 1; i < nums.length; i++){ + + tree.add(nums[i]); + + if(tree.nearSub(nums[i]) <= t){ + return true; + } + + if(tree.size > k){ + tree.remove(nums[p++]); + } + } + + return false; + } +} diff --git a/contains-duplicate-iii/index.md b/contains-duplicate-iii/index.md new file mode 100644 index 0000000..a2aed57 --- /dev/null +++ b/contains-duplicate-iii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Contains Duplicate III +date: 2015-06-02 01:36:35+08:00 +leetcode_id: 220 +--- +{% include_relative README.md %} From c05d570366628f196f6018daff19eeffd0ce3886 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 4 Jun 2015 23:48:13 +0800 Subject: [PATCH 160/195] add max squre --- maximal-square/README.md | 0 maximal-square/Solution.java | 46 ++++++++++++++++++++++++++++++++++++ maximal-square/index.md | 7 ++++++ 3 files changed, 53 insertions(+) create mode 100644 maximal-square/README.md create mode 100644 maximal-square/Solution.java create mode 100644 maximal-square/index.md diff --git a/maximal-square/README.md b/maximal-square/README.md new file mode 100644 index 0000000..e69de29 diff --git a/maximal-square/Solution.java b/maximal-square/Solution.java new file mode 100644 index 0000000..9350e23 --- /dev/null +++ b/maximal-square/Solution.java @@ -0,0 +1,46 @@ +public class Solution { + + int maximalSquare(char[][] matrix, final int x, final int y){ + int l = 1; + + done: + while(true){ + + for(int i = 0; i <= l; i++){ + + if(x + l >= matrix.length || y + l >= matrix[0].length){ + break done; + } + + + if(matrix[x + l][y + i] != '1'){ + break done; + } + + if(matrix[x + i][y + l] != '1'){ + break done; + } + + } + + l++; + } + + return l * l; + } + + public int maximalSquare(char[][] matrix) { + + int max = 0; + + for(int x = 0; x < matrix.length; x++){ + for(int y = 0; y < matrix[0].length; y++){ + if(matrix[x][y] == '1'){ + max = Math.max(max, maximalSquare(matrix, x, y)); + } + } + } + + return max; + } +} diff --git a/maximal-square/index.md b/maximal-square/index.md new file mode 100644 index 0000000..142c600 --- /dev/null +++ b/maximal-square/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Maximal Square +date: 2015-06-04 23:46:46+08:00 +leetcode_id: 221 +--- +{% include_relative README.md %} From eca06c9be247266a6eb0146ac0cc525dc80cf617 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 8 Jun 2015 00:31:57 +0800 Subject: [PATCH 161/195] add count complete tree --- count-complete-tree-nodes/README.md | 0 count-complete-tree-nodes/Solution.java | 70 +++++++++++++++++++++++++ count-complete-tree-nodes/index.md | 7 +++ 3 files changed, 77 insertions(+) create mode 100644 count-complete-tree-nodes/README.md create mode 100644 count-complete-tree-nodes/Solution.java create mode 100644 count-complete-tree-nodes/index.md diff --git a/count-complete-tree-nodes/README.md b/count-complete-tree-nodes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/count-complete-tree-nodes/Solution.java b/count-complete-tree-nodes/Solution.java new file mode 100644 index 0000000..2f9feb6 --- /dev/null +++ b/count-complete-tree-nodes/Solution.java @@ -0,0 +1,70 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int height(TreeNode root){ + if(root == null) return 0; + + return 1 + height(root.left); + } + + + int leaves = 0; + boolean stop = false; + + void countLeaves(TreeNode root, int heightToLeaf){ + + if(root == null) return; + + if(stop) return; + + if(heightToLeaf == 2) { + + if(root.right != null){ + leaves += 2; + } else { + + // at lease one is null + stop = true; + + if(root.left != null) { + leaves += 1; + } + } + + + return; + } + + countLeaves(root.left, heightToLeaf - 1); + countLeaves(root.right, heightToLeaf - 1); + } + + int perfectTreeNodeCount(int height){ + if(height == 0) return 0; + if(height == 1) return 1; + + return (int)Math.pow(2, height) - 1; + } + + public int countNodes(TreeNode root) { + + int h = height(root); + + countLeaves(root, h); + + if(!stop){ + // perfect tree + return perfectTreeNodeCount(h); + } + + return perfectTreeNodeCount(h - 1) + leaves; + } +} diff --git a/count-complete-tree-nodes/index.md b/count-complete-tree-nodes/index.md new file mode 100644 index 0000000..d19bd9f --- /dev/null +++ b/count-complete-tree-nodes/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Count Complete Tree Nodes +date: 2015-06-08 00:30:07+08:00 +leetcode_id: 222 +--- +{% include_relative README.md %} From f36eaa8b32183c63de234d87038fdb038116063b Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 8 Jun 2015 23:33:59 +0800 Subject: [PATCH 162/195] add rect area --- rectangle-area/README.md | 0 rectangle-area/Solution.java | 35 +++++++++++++++++++++++++++++++++++ rectangle-area/index.md | 7 +++++++ 3 files changed, 42 insertions(+) create mode 100644 rectangle-area/README.md create mode 100644 rectangle-area/Solution.java create mode 100644 rectangle-area/index.md diff --git a/rectangle-area/README.md b/rectangle-area/README.md new file mode 100644 index 0000000..e69de29 diff --git a/rectangle-area/Solution.java b/rectangle-area/Solution.java new file mode 100644 index 0000000..d26cfec --- /dev/null +++ b/rectangle-area/Solution.java @@ -0,0 +1,35 @@ +public class Solution { + + int area(int x1, int y1, int x2, int y2){ + return (y2 - y1) * (x2 - x1); + } + + public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + + // make sure left is left + if(A > E){ + return computeArea(E, F, G, H, A, B, C, D); + } + + int a = area(A, B, C, D) + area(E, F, G, H); + + // no share case1 + // [ ]C + // E[ ] + if(C < E){ + return a; + } + + // no share case2 + // [ ]B + // + // [ ]H + + if(B > H || F > D){ + return a; + } + + // remove share + return a - area(E, Math.max(B, F), Math.min(C, G), Math.min(D, H)); + } +} diff --git a/rectangle-area/index.md b/rectangle-area/index.md new file mode 100644 index 0000000..3303cd1 --- /dev/null +++ b/rectangle-area/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Rectangle Area +date: 2015-06-08 23:32:33+08:00 +leetcode_id: 223 +--- +{% include_relative README.md %} From 059846c9bf710942bf66925869b6c4de11734e63 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 28 Jun 2015 15:58:34 +0800 Subject: [PATCH 163/195] add 3 easier problems --- implement-stack-using-queues/MyStack.java | 1 + implement-stack-using-queues/README.md | 0 implement-stack-using-queues/Solution.java | 34 ++++++++++++++++++ implement-stack-using-queues/index.md | 7 ++++ invert-binary-tree/README.md | 0 invert-binary-tree/Solution.java | 0 invert-binary-tree/index.md | 7 ++++ summary-ranges/README.md | 0 summary-ranges/Solution.java | 41 ++++++++++++++++++++++ summary-ranges/index.md | 7 ++++ 10 files changed, 97 insertions(+) create mode 120000 implement-stack-using-queues/MyStack.java create mode 100644 implement-stack-using-queues/README.md create mode 100644 implement-stack-using-queues/Solution.java create mode 100644 implement-stack-using-queues/index.md create mode 100644 invert-binary-tree/README.md create mode 100644 invert-binary-tree/Solution.java create mode 100644 invert-binary-tree/index.md create mode 100644 summary-ranges/README.md create mode 100644 summary-ranges/Solution.java create mode 100644 summary-ranges/index.md diff --git a/implement-stack-using-queues/MyStack.java b/implement-stack-using-queues/MyStack.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/implement-stack-using-queues/MyStack.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/implement-stack-using-queues/README.md b/implement-stack-using-queues/README.md new file mode 100644 index 0000000..e69de29 diff --git a/implement-stack-using-queues/Solution.java b/implement-stack-using-queues/Solution.java new file mode 100644 index 0000000..075ca38 --- /dev/null +++ b/implement-stack-using-queues/Solution.java @@ -0,0 +1,34 @@ +class MyStack { + + Queue queue = new LinkedList<>(); + + // Push element x onto stack. + public void push(int x) { + Queue swap = new LinkedList<>(); + + swap.add(x); + + while(!queue.isEmpty()){ + swap.add(queue.remove()); + } + + queue = swap; + } + + // Removes the element on top of the stack. + public void pop() { + // pop from front + queue.remove(); + } + + // Get the top element. + public int top() { + // peek from front + return queue.peek(); + } + + // Return whether the stack is empty. + public boolean empty() { + return queue.isEmpty(); + } +} diff --git a/implement-stack-using-queues/index.md b/implement-stack-using-queues/index.md new file mode 100644 index 0000000..25ede72 --- /dev/null +++ b/implement-stack-using-queues/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Implement Stack using Queues +date: 2015-06-28 15:56:53+08:00 +leetcode_id: 225 +--- +{% include_relative README.md %} diff --git a/invert-binary-tree/README.md b/invert-binary-tree/README.md new file mode 100644 index 0000000..e69de29 diff --git a/invert-binary-tree/Solution.java b/invert-binary-tree/Solution.java new file mode 100644 index 0000000..e69de29 diff --git a/invert-binary-tree/index.md b/invert-binary-tree/index.md new file mode 100644 index 0000000..451ca81 --- /dev/null +++ b/invert-binary-tree/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Invert Binary Tree +date: 2015-06-28 15:39:51+08:00 +leetcode_id: 226 +--- +{% include_relative README.md %} diff --git a/summary-ranges/README.md b/summary-ranges/README.md new file mode 100644 index 0000000..e69de29 diff --git a/summary-ranges/Solution.java b/summary-ranges/Solution.java new file mode 100644 index 0000000..f37335b --- /dev/null +++ b/summary-ranges/Solution.java @@ -0,0 +1,41 @@ +public class Solution { + + static class Range { + + int st; + int ed; + + Range(int st){ + this.st = st; + this.ed = st; + } + + public String toString(){ + if(ed == st) return "" + st; + + return st + "->" + ed; + } + } + + public List summaryRanges(int[] nums) { + + ArrayList rt = new ArrayList<>(); + + if(nums.length == 0) return rt; + + Range r = new Range(nums[0]); + + for(int i = 1; i < nums.length; i++){ + if(nums[i] - r.ed == 1){ + r.ed = nums[i]; + } else { + rt.add(r.toString()); + r = new Range(nums[i]); + } + } + + rt.add(r.toString()); + + return rt; + } +} diff --git a/summary-ranges/index.md b/summary-ranges/index.md new file mode 100644 index 0000000..6fb65ed --- /dev/null +++ b/summary-ranges/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Summary Ranges +date: 2015-06-28 15:35:53+08:00 +leetcode_id: 228 +--- +{% include_relative README.md %} From 759d65cdfc1da526a4acd697dcf85ff394a1e1ae Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 28 Jun 2015 21:11:36 +0800 Subject: [PATCH 164/195] code did not save before push --- invert-binary-tree/Solution.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/invert-binary-tree/Solution.java b/invert-binary-tree/Solution.java index e69de29..f07e3a5 100644 --- a/invert-binary-tree/Solution.java +++ b/invert-binary-tree/Solution.java @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode invertTree(TreeNode root) { + if(root == null) return null; + + TreeNode newLeft = invertTree(root.right); + TreeNode newRight = invertTree(root.left); + + root.left = newLeft; + root.right = newRight; + + return root; + } +} From a01c199b47ca6d07602b11d51876e0fdb711a6ea Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 29 Jun 2015 00:21:54 +0800 Subject: [PATCH 165/195] add two basic calculator --- basic-calculator-ii/README.md | 0 basic-calculator-ii/Solution.java | 183 ++++++++++++++++++++++++++++++ basic-calculator-ii/index.md | 7 ++ basic-calculator/README.md | 0 basic-calculator/Solution.java | 183 ++++++++++++++++++++++++++++++ basic-calculator/index.md | 7 ++ 6 files changed, 380 insertions(+) create mode 100644 basic-calculator-ii/README.md create mode 100644 basic-calculator-ii/Solution.java create mode 100644 basic-calculator-ii/index.md create mode 100644 basic-calculator/README.md create mode 100644 basic-calculator/Solution.java create mode 100644 basic-calculator/index.md diff --git a/basic-calculator-ii/README.md b/basic-calculator-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/basic-calculator-ii/Solution.java b/basic-calculator-ii/Solution.java new file mode 100644 index 0000000..9976235 --- /dev/null +++ b/basic-calculator-ii/Solution.java @@ -0,0 +1,183 @@ +public class Solution { + enum TokenType { DIGIT, OP } + + static class Token { + TokenType type; + int val; + + public Token(int val, TokenType type) { + this.val = val; + this.type = type; + } + } + + static final Token EOL = new Token(0, TokenType.OP); + + static final Token[] TOKENS = new Token[256]; + + static { + TOKENS['+'] = new Token('+', TokenType.OP); + TOKENS['-'] = new Token('-', TokenType.OP); + TOKENS['*'] = new Token('*', TokenType.OP); + TOKENS['/'] = new Token('/', TokenType.OP); + TOKENS['('] = new Token('(', TokenType.OP); + TOKENS[')'] = new Token(')', TokenType.OP); + } + + static class Tokenizer { + + Scanner scanner; + + Tokenizer(String s){ + scanner = new Scanner(s); + scanner.useDelimiter(""); + } + + Token next(){ + if(!scanner.hasNext()){ + return EOL; + } + + boolean num = false; + int buf = 0; + while (scanner.hasNextInt()){ + num = true; + buf = buf * 10 + scanner.nextInt(); + } + + if(num){ + return new Token(buf, TokenType.DIGIT); + } + + char c = scanner.next().charAt(0); + + if(TOKENS[c] != null){ + return TOKENS[c]; + } + + return next(); + } + } + + static class RPNCalculator { + LinkedList stack = new LinkedList<>(); + + void addToken(Token t){ + if(t.type == TokenType.OP){ + + int v2 = stack.pop(); + int v1 = stack.pop(); + + switch (t.val){ + case '+': + stack.push(v1 + v2); + break; + case '-': + stack.push(v1 - v2); + break; + case '*': + stack.push(v1 * v2); + break; + case '/': + stack.push(v1 / v2); + break; + default: + // cant happen + } + + } else { // DIGIT + stack.push(t.val); + } + } + + int val(){ + return stack.peek(); + } + } + + public int calculate(String s) { + + RPNCalculator calculator = new RPNCalculator(); + + Tokenizer tokenizer = new Tokenizer(s); + + LinkedList op = new LinkedList<>(); + + Token t; + + next: + while ((t = tokenizer.next()) != EOL){ + + // convert to RPN + + if(t.type == TokenType.DIGIT){ + calculator.addToken(t); + + } else { // type == OP + + retry: + while(true) { + + if(op.isEmpty()){ + op.push(t); + continue next; + } + + Token top = op.peek(); + + switch (t.val) { + case '(': + op.push(t); + break; + + case '+': + case '-': + if (top.val == '+' || top.val == '-' || + top.val == '*' || top.val == '/') { + + calculator.addToken(op.pop()); + continue retry; + } + + op.push(t); + + break; + + case '*': + case '/': + if (top.val == '*' || top.val == '/') { + calculator.addToken(op.pop()); + continue retry; + } + + op.push(t); + + break; + + case ')': + + while (!op.isEmpty()) { + top = op.pop(); + + if (top.val == '(') continue next; + + calculator.addToken(top); + } + + default: + // cant happen + } + + continue next; + } + } + } + + while (!op.isEmpty()){ + calculator.addToken(op.pop()); + } + + return calculator.val(); + } + +} diff --git a/basic-calculator-ii/index.md b/basic-calculator-ii/index.md new file mode 100644 index 0000000..c076eed --- /dev/null +++ b/basic-calculator-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Basic Calculator II +date: 2015-06-29 00:20:12+08:00 +leetcode_id: 228 +--- +{% include_relative README.md %} diff --git a/basic-calculator/README.md b/basic-calculator/README.md new file mode 100644 index 0000000..e69de29 diff --git a/basic-calculator/Solution.java b/basic-calculator/Solution.java new file mode 100644 index 0000000..9976235 --- /dev/null +++ b/basic-calculator/Solution.java @@ -0,0 +1,183 @@ +public class Solution { + enum TokenType { DIGIT, OP } + + static class Token { + TokenType type; + int val; + + public Token(int val, TokenType type) { + this.val = val; + this.type = type; + } + } + + static final Token EOL = new Token(0, TokenType.OP); + + static final Token[] TOKENS = new Token[256]; + + static { + TOKENS['+'] = new Token('+', TokenType.OP); + TOKENS['-'] = new Token('-', TokenType.OP); + TOKENS['*'] = new Token('*', TokenType.OP); + TOKENS['/'] = new Token('/', TokenType.OP); + TOKENS['('] = new Token('(', TokenType.OP); + TOKENS[')'] = new Token(')', TokenType.OP); + } + + static class Tokenizer { + + Scanner scanner; + + Tokenizer(String s){ + scanner = new Scanner(s); + scanner.useDelimiter(""); + } + + Token next(){ + if(!scanner.hasNext()){ + return EOL; + } + + boolean num = false; + int buf = 0; + while (scanner.hasNextInt()){ + num = true; + buf = buf * 10 + scanner.nextInt(); + } + + if(num){ + return new Token(buf, TokenType.DIGIT); + } + + char c = scanner.next().charAt(0); + + if(TOKENS[c] != null){ + return TOKENS[c]; + } + + return next(); + } + } + + static class RPNCalculator { + LinkedList stack = new LinkedList<>(); + + void addToken(Token t){ + if(t.type == TokenType.OP){ + + int v2 = stack.pop(); + int v1 = stack.pop(); + + switch (t.val){ + case '+': + stack.push(v1 + v2); + break; + case '-': + stack.push(v1 - v2); + break; + case '*': + stack.push(v1 * v2); + break; + case '/': + stack.push(v1 / v2); + break; + default: + // cant happen + } + + } else { // DIGIT + stack.push(t.val); + } + } + + int val(){ + return stack.peek(); + } + } + + public int calculate(String s) { + + RPNCalculator calculator = new RPNCalculator(); + + Tokenizer tokenizer = new Tokenizer(s); + + LinkedList op = new LinkedList<>(); + + Token t; + + next: + while ((t = tokenizer.next()) != EOL){ + + // convert to RPN + + if(t.type == TokenType.DIGIT){ + calculator.addToken(t); + + } else { // type == OP + + retry: + while(true) { + + if(op.isEmpty()){ + op.push(t); + continue next; + } + + Token top = op.peek(); + + switch (t.val) { + case '(': + op.push(t); + break; + + case '+': + case '-': + if (top.val == '+' || top.val == '-' || + top.val == '*' || top.val == '/') { + + calculator.addToken(op.pop()); + continue retry; + } + + op.push(t); + + break; + + case '*': + case '/': + if (top.val == '*' || top.val == '/') { + calculator.addToken(op.pop()); + continue retry; + } + + op.push(t); + + break; + + case ')': + + while (!op.isEmpty()) { + top = op.pop(); + + if (top.val == '(') continue next; + + calculator.addToken(top); + } + + default: + // cant happen + } + + continue next; + } + } + } + + while (!op.isEmpty()){ + calculator.addToken(op.pop()); + } + + return calculator.val(); + } + +} diff --git a/basic-calculator/index.md b/basic-calculator/index.md new file mode 100644 index 0000000..3b73b31 --- /dev/null +++ b/basic-calculator/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Basic Calculator +date: 2015-06-29 00:20:02+08:00 +leetcode_id: 224 +--- +{% include_relative README.md %} From c40c5b5971ff4db1b6ad1ef58a472357c0b23dea Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 29 Jun 2015 00:23:00 +0800 Subject: [PATCH 166/195] fix leetcode id --- basic-calculator-ii/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/basic-calculator-ii/index.md b/basic-calculator-ii/index.md index c076eed..78f146e 100644 --- a/basic-calculator-ii/index.md +++ b/basic-calculator-ii/index.md @@ -2,6 +2,6 @@ layout: solution title: Basic Calculator II date: 2015-06-29 00:20:12+08:00 -leetcode_id: 228 +leetcode_id: 227 --- {% include_relative README.md %} From c4343314c10195298d473c290064c23cd36b3efc Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 29 Jun 2015 13:43:24 +0800 Subject: [PATCH 167/195] add major ele ii --- majority-element-ii/README.md | 0 majority-element-ii/Solution.java | 50 +++++++++++++++++++++++++++++++ majority-element-ii/index.md | 7 +++++ 3 files changed, 57 insertions(+) create mode 100644 majority-element-ii/README.md create mode 100644 majority-element-ii/Solution.java create mode 100644 majority-element-ii/index.md diff --git a/majority-element-ii/README.md b/majority-element-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/majority-element-ii/Solution.java b/majority-element-ii/Solution.java new file mode 100644 index 0000000..a4d9b33 --- /dev/null +++ b/majority-element-ii/Solution.java @@ -0,0 +1,50 @@ +public class Solution { + public List majorityElement(int[] nums) { + if(nums.length == 0) return Collections.emptyList(); + + int n1 = nums[0]; + int n2 = nums[0]; + + int c1 = 0; + int c2 = 0; + + for(int i = 0; i < nums.length; i++){ + + // put to an empty slot + if(c1 <= 0 && nums[i] != n2){ + n1 = nums[i]; + c1 = 1; + continue; + } + + if(c2 <= 0 && nums[i] != n1){ + n2 = nums[i]; + c2 = 1; + continue; + } + + // add count + if(nums[i] == n1){ + c1++; + continue; + } + + if(nums[i] == n2){ + c2++; + continue; + } + + // no match + + c1--; + c2--; + } + + // faint + return new ArrayList<>(IntStream.of(n1, n2) + .filter(n -> + Arrays.stream(nums).filter(i -> n == i).count() > nums.length / 3) + .boxed() + .collect(Collectors.toSet())); + } +} diff --git a/majority-element-ii/index.md b/majority-element-ii/index.md new file mode 100644 index 0000000..2e262bc --- /dev/null +++ b/majority-element-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Majority Element II +date: 2015-06-29 13:42:29+08:00 +leetcode_id: 229 +--- +{% include_relative README.md %} From 821153894e0d62639712707163ca7f5165be592e Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 2 Jul 2015 14:17:56 +0800 Subject: [PATCH 168/195] add k smallest in bst --- kth-smallest-element-in-a-bst/README.md | 0 kth-smallest-element-in-a-bst/Solution.java | 51 +++++++++++++++++++++ kth-smallest-element-in-a-bst/index.md | 7 +++ 3 files changed, 58 insertions(+) create mode 100644 kth-smallest-element-in-a-bst/README.md create mode 100644 kth-smallest-element-in-a-bst/Solution.java create mode 100644 kth-smallest-element-in-a-bst/index.md diff --git a/kth-smallest-element-in-a-bst/README.md b/kth-smallest-element-in-a-bst/README.md new file mode 100644 index 0000000..e69de29 diff --git a/kth-smallest-element-in-a-bst/Solution.java b/kth-smallest-element-in-a-bst/Solution.java new file mode 100644 index 0000000..0af45bc --- /dev/null +++ b/kth-smallest-element-in-a-bst/Solution.java @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + boolean reachLeftMost = false; + boolean stop = false; + + int kth = 0; + int k = 0; + + void search(TreeNode root) { + + if(stop){ + return; + } + + // visit + if(root == null){ + reachLeftMost = true; + return; + } + + search(root.left); + + if(reachLeftMost) { + k--; + } + + if(k == 0){ + kth = root.val; + stop = true; + return; + } + + search(root.right); + } + + public int kthSmallest(TreeNode root, int k) { + this.k = k; + search(root); + + return kth; + } +} diff --git a/kth-smallest-element-in-a-bst/index.md b/kth-smallest-element-in-a-bst/index.md new file mode 100644 index 0000000..e34b4f0 --- /dev/null +++ b/kth-smallest-element-in-a-bst/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Kth Smallest Element in a BST +date: 2015-07-02 14:16:21+08:00 +leetcode_id: 230 +--- +{% include_relative README.md %} From 6727f8f342c8b5b4f234007eda82b7c7963cf609 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 6 Jul 2015 23:01:20 +0800 Subject: [PATCH 169/195] pow of two --- power-of-two/README.md | 0 power-of-two/Solution.java | 10 ++++++++++ power-of-two/index.md | 7 +++++++ 3 files changed, 17 insertions(+) create mode 100644 power-of-two/README.md create mode 100644 power-of-two/Solution.java create mode 100644 power-of-two/index.md diff --git a/power-of-two/README.md b/power-of-two/README.md new file mode 100644 index 0000000..e69de29 diff --git a/power-of-two/Solution.java b/power-of-two/Solution.java new file mode 100644 index 0000000..9a4aae2 --- /dev/null +++ b/power-of-two/Solution.java @@ -0,0 +1,10 @@ +public class Solution { + public boolean isPowerOfTwo(int n) { + if(n == 0) return false; + if(n == 1) return true; + + if(n % 2 == 1) return false; + + return isPowerOfTwo(n / 2); + } +} diff --git a/power-of-two/index.md b/power-of-two/index.md new file mode 100644 index 0000000..de9ef4b --- /dev/null +++ b/power-of-two/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Power of Two +date: 2015-07-06 23:00:26+08:00 +leetcode_id: 231 +--- +{% include_relative README.md %} From ef4aea98e09ac8b586acb5ba7d7a9068fc185072 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 7 Jul 2015 21:05:48 +0800 Subject: [PATCH 170/195] add queue use stack --- implement-queue-using-stacks/README.md | 0 implement-queue-using-stacks/Solution.java | 35 ++++++++++++++++++++++ implement-queue-using-stacks/index.md | 7 +++++ 3 files changed, 42 insertions(+) create mode 100644 implement-queue-using-stacks/README.md create mode 100644 implement-queue-using-stacks/Solution.java create mode 100644 implement-queue-using-stacks/index.md diff --git a/implement-queue-using-stacks/README.md b/implement-queue-using-stacks/README.md new file mode 100644 index 0000000..e69de29 diff --git a/implement-queue-using-stacks/Solution.java b/implement-queue-using-stacks/Solution.java new file mode 100644 index 0000000..c5a336a --- /dev/null +++ b/implement-queue-using-stacks/Solution.java @@ -0,0 +1,35 @@ +class MyQueue { + + // should use Deque stack in modern java + Stack stack = new Stack<>(); + + // Push element x to the back of queue. + public void push(int x) { + Stack rev = new Stack<>(); + + while(!stack.empty()){ + rev.push(stack.pop()); + } + + rev.push(x); + + while(!rev.empty()){ + stack.push(rev.pop()); + } + } + + // Removes the element from in front of queue. + public void pop() { + stack.pop(); + } + + // Get the front element. + public int peek() { + return stack.peek(); + } + + // Return whether the queue is empty. + public boolean empty() { + return stack.empty(); + } +} diff --git a/implement-queue-using-stacks/index.md b/implement-queue-using-stacks/index.md new file mode 100644 index 0000000..90c5ceb --- /dev/null +++ b/implement-queue-using-stacks/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Implement Queue using Stacks +date: 2015-07-07 21:04:46+08:00 +leetcode_id: 232 +--- +{% include_relative README.md %} From 686aa05f4c153462f474d9f2dd43f8d3f032cdf2 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 8 Jul 2015 00:41:33 +0800 Subject: [PATCH 171/195] num of digit 1 --- number-of-digit-one/README.md | 0 number-of-digit-one/Solution.java | 57 +++++++++++++++++++++++++++++++ number-of-digit-one/index.md | 7 ++++ 3 files changed, 64 insertions(+) create mode 100644 number-of-digit-one/README.md create mode 100644 number-of-digit-one/Solution.java create mode 100644 number-of-digit-one/index.md diff --git a/number-of-digit-one/README.md b/number-of-digit-one/README.md new file mode 100644 index 0000000..e69de29 diff --git a/number-of-digit-one/Solution.java b/number-of-digit-one/Solution.java new file mode 100644 index 0000000..b90839a --- /dev/null +++ b/number-of-digit-one/Solution.java @@ -0,0 +1,57 @@ +public class Solution { + + // return { highest digit, floor(n) } + // 'floor' here has a naming problem... + // named it exactly later + // floor(101) = 100 + // floor(92) = 90 + // floor(10111) = 10000 + + int[] N = {100000000, 10000, 100, 10}; + + int[] extractHighest(int x){ + int e = 1; + + for(int n : N){ + if(x >= n){ + x /= n; + e *= n; + } + } + + return new int[]{x, x * e}; + } + + Map cache = new HashMap<>(); + + public int countDigitOne(int n) { + + if(n <= 0) return 0; + if(n < 10) return 1; + + Integer cached = cache.get(n); + + if(cached != null){ + return cached; + } + + int[] e = extractHighest(n); + + int h = e[0]; + int f = e[1]; + + int rest = n - f; + + int plus = 0; + + if(h == 1){ + plus = rest + 1; + } + + int c = plus + countDigitOne(f - 1) + countDigitOne(rest); + + cache.put(n, c); + + return c; + } +} diff --git a/number-of-digit-one/index.md b/number-of-digit-one/index.md new file mode 100644 index 0000000..2e2acbd --- /dev/null +++ b/number-of-digit-one/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Number of Digit One +date: 2015-07-08 00:39:17+08:00 +leetcode_id: 233 +--- +{% include_relative README.md %} From 84277f537cbac2a8a6ad081561301e6949dff5fe Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 12 Jul 2015 17:01:28 +0800 Subject: [PATCH 172/195] add lca of bst and pal linked list --- .../README.md | 0 .../Solution.java | 28 ++++++++++ .../index.md | 7 +++ palindrome-linked-list/README.md | 0 palindrome-linked-list/Solution.java | 56 +++++++++++++++++++ palindrome-linked-list/index.md | 7 +++ 6 files changed, 98 insertions(+) create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/README.md create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/Solution.java create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/index.md create mode 100644 palindrome-linked-list/README.md create mode 100644 palindrome-linked-list/Solution.java create mode 100644 palindrome-linked-list/index.md diff --git a/lowest-common-ancestor-of-a-binary-search-tree/README.md b/lowest-common-ancestor-of-a-binary-search-tree/README.md new file mode 100644 index 0000000..e69de29 diff --git a/lowest-common-ancestor-of-a-binary-search-tree/Solution.java b/lowest-common-ancestor-of-a-binary-search-tree/Solution.java new file mode 100644 index 0000000..1047289 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/Solution.java @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // make sure p < q + if(p.val > q.val) return lowestCommonAncestor(root, q, p); + + // find p <= root <= q + while(!(p.val <= root.val && root.val <= q.val)){ + + if(root.val > q.val){ + root = root.left; + } else { // root.val < p.val + root = root.right; + } + + } + + return root; + } +} diff --git a/lowest-common-ancestor-of-a-binary-search-tree/index.md b/lowest-common-ancestor-of-a-binary-search-tree/index.md new file mode 100644 index 0000000..5dae6aa --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Lowest Common Ancestor of a Binary Search Tree +date: 2015-07-12 16:47:16+08:00 +leetcode_id: 235 +--- +{% include_relative README.md %} diff --git a/palindrome-linked-list/README.md b/palindrome-linked-list/README.md new file mode 100644 index 0000000..e69de29 diff --git a/palindrome-linked-list/Solution.java b/palindrome-linked-list/Solution.java new file mode 100644 index 0000000..0827711 --- /dev/null +++ b/palindrome-linked-list/Solution.java @@ -0,0 +1,56 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +public class Solution { + ListNode mid(ListNode head){ + + ListNode fast = head; + ListNode slow = head; + + while(fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + } + + return slow; + } + + ListNode reverse(ListNode head) { + ListNode prev = null; + + while(head != null){ + + ListNode t = head.next; + + head.next = prev; + prev = head; + + head = t; + } + + return prev; + } + + public boolean isPalindrome(ListNode head) { + ListNode m = mid(head); + + m = reverse(m); + + while(m != head && m != null){ + + if(m.val != head.val){ + return false; + } + + m = m.next; + head = head.next; + } + + return true; + } +} diff --git a/palindrome-linked-list/index.md b/palindrome-linked-list/index.md new file mode 100644 index 0000000..bd04d46 --- /dev/null +++ b/palindrome-linked-list/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Palindrome Linked List +date: 2015-07-12 17:00:15+08:00 +leetcode_id: 234 +--- +{% include_relative README.md %} From cc228fc78bba2259f197c203204aa6718cee5d00 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 26 Jul 2015 14:44:03 +0800 Subject: [PATCH 173/195] add 2d matrix ii and del node --- delete-node-in-a-linked-list/README.md | 0 delete-node-in-a-linked-list/Solution.java | 14 ++++++++++ delete-node-in-a-linked-list/index.md | 7 +++++ search-a-2d-matrix-ii/README.md | 0 search-a-2d-matrix-ii/Solution.java | 32 ++++++++++++++++++++++ search-a-2d-matrix-ii/index.md | 7 +++++ 6 files changed, 60 insertions(+) create mode 100644 delete-node-in-a-linked-list/README.md create mode 100644 delete-node-in-a-linked-list/Solution.java create mode 100644 delete-node-in-a-linked-list/index.md create mode 100644 search-a-2d-matrix-ii/README.md create mode 100644 search-a-2d-matrix-ii/Solution.java create mode 100644 search-a-2d-matrix-ii/index.md diff --git a/delete-node-in-a-linked-list/README.md b/delete-node-in-a-linked-list/README.md new file mode 100644 index 0000000..e69de29 diff --git a/delete-node-in-a-linked-list/Solution.java b/delete-node-in-a-linked-list/Solution.java new file mode 100644 index 0000000..9e83a6f --- /dev/null +++ b/delete-node-in-a-linked-list/Solution.java @@ -0,0 +1,14 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +public class Solution { + public void deleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} diff --git a/delete-node-in-a-linked-list/index.md b/delete-node-in-a-linked-list/index.md new file mode 100644 index 0000000..80f716b --- /dev/null +++ b/delete-node-in-a-linked-list/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Delete Node in a Linked List +date: 2015-07-26 14:42:29+08:00 +leetcode_id: 237 +--- +{% include_relative README.md %} diff --git a/search-a-2d-matrix-ii/README.md b/search-a-2d-matrix-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/search-a-2d-matrix-ii/Solution.java b/search-a-2d-matrix-ii/Solution.java new file mode 100644 index 0000000..dbd55ab --- /dev/null +++ b/search-a-2d-matrix-ii/Solution.java @@ -0,0 +1,32 @@ +public class Solution { + + boolean searchMatrix(int[][] matrix, int stX, int stY, int edX, int edY, int target) { + + if (stX >= edX || stY >= edY) return false; + + int max = matrix[edX - 1][edY - 1]; + int min = matrix[stX][stY]; + + // min <= target <= max + if (min <= target && target <= max){ + + int mdX = (stX + edX) / 2; + int mdY = (stY + edY) / 2; + + if(matrix[mdX][mdY] == target){ + return true; + } + + return searchMatrix(matrix, stX, stY, mdX, mdY, target) || + searchMatrix(matrix, stX, mdY, mdX, edY, target) || + searchMatrix(matrix, mdX, stY, edX, mdY, target) || + searchMatrix(matrix, mdX, mdY, edX, edY, target); + } + + return false; + } + + public boolean searchMatrix(int[][] matrix, int target) { + return searchMatrix(matrix, 0, 0, matrix.length, matrix[0].length, target); + } +} diff --git a/search-a-2d-matrix-ii/index.md b/search-a-2d-matrix-ii/index.md new file mode 100644 index 0000000..c67abeb --- /dev/null +++ b/search-a-2d-matrix-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Search a 2D Matrix II +date: 2015-07-26 14:40:48+08:00 +leetcode_id: 240 +--- +{% include_relative README.md %} From d7254556ea31d6dda0b9015fae7a136ac9dac9fe Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 26 Jul 2015 16:54:32 +0800 Subject: [PATCH 174/195] add lca --- .../README.md | 0 .../Solution.java | 57 +++++++++++++++++++ .../index.md | 7 +++ 3 files changed, 64 insertions(+) create mode 100644 lowest-common-ancestor-of-a-binary-tree/README.md create mode 100644 lowest-common-ancestor-of-a-binary-tree/Solution.java create mode 100644 lowest-common-ancestor-of-a-binary-tree/index.md diff --git a/lowest-common-ancestor-of-a-binary-tree/README.md b/lowest-common-ancestor-of-a-binary-tree/README.md new file mode 100644 index 0000000..e69de29 diff --git a/lowest-common-ancestor-of-a-binary-tree/Solution.java b/lowest-common-ancestor-of-a-binary-tree/Solution.java new file mode 100644 index 0000000..99fef31 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-tree/Solution.java @@ -0,0 +1,57 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode lca; + + TreeNode other; + + boolean containOther(TreeNode root){ + + if(root == null) return false; + + if(root == other) return true; + + return containOther(root.left) || containOther(root.right); + } + + void inorder(TreeNode root, TreeNode p, TreeNode q){ + if(lca != null) return; + + if(root == null) return; + + if(other == null) inorder(root.left, p, q); + + if(other == null){ + if(root == p){ + other = q; + } else if (root == q){ + other = p; + } + } + + if(other != null){ + // left contain one, need other + if(root == other || containOther(root.right)){ + lca = root; + } + } + + if(other == null) inorder(root.right, p, q); + } + + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // a bit ugly + inorder(root, p, q); + + return lca; + } +} diff --git a/lowest-common-ancestor-of-a-binary-tree/index.md b/lowest-common-ancestor-of-a-binary-tree/index.md new file mode 100644 index 0000000..ef8ac7f --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-tree/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Lowest Common Ancestor of a Binary Tree +date: 2015-07-26 16:03:27+08:00 +leetcode_id: 236 +--- +{% include_relative README.md %} From e11b290d1c5ea187489609401aa7d282840071b1 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 26 Jul 2015 16:56:10 +0800 Subject: [PATCH 175/195] add sliding win max --- sliding-window-maximum/README.md | 0 sliding-window-maximum/Solution.java | 52 ++++++++++++++++++++++++++++ sliding-window-maximum/index.md | 7 ++++ 3 files changed, 59 insertions(+) create mode 100644 sliding-window-maximum/README.md create mode 100644 sliding-window-maximum/Solution.java create mode 100644 sliding-window-maximum/index.md diff --git a/sliding-window-maximum/README.md b/sliding-window-maximum/README.md new file mode 100644 index 0000000..e69de29 diff --git a/sliding-window-maximum/Solution.java b/sliding-window-maximum/Solution.java new file mode 100644 index 0000000..947c970 --- /dev/null +++ b/sliding-window-maximum/Solution.java @@ -0,0 +1,52 @@ +public class Solution { + + static class SlidingMaxQueue { + + int[] nums; + int k; + + LinkedList queue = new LinkedList<>(); + + SlidingMaxQueue(int[] nums, int k){ + this.nums = nums; + this.k = k; + } + + int max(){ + return nums[queue.peekFirst()]; + } + + void add(int i){ + + if(i >= nums.length) return; + + // remove invalid index + while(!queue.isEmpty() && queue.peekFirst() <= i - k){ + queue.pollFirst(); + } + + // remove nums < current; + while(!queue.isEmpty() && nums[queue.peekLast()] < nums[i]){ + queue.pollLast(); + } + + queue.add(i); + } + } + + public int[] maxSlidingWindow(int[] nums, int k) { + + int[] T = new int[Math.min(nums.length - k + 1, nums.length)]; + + SlidingMaxQueue Q = new SlidingMaxQueue(nums, k); + + Q.add(0); + + for(int i = 1; i <= nums.length; i++){ + T[Math.max(i - k, 0)] = Q.max(); + Q.add(i); + } + + return T; + } +} diff --git a/sliding-window-maximum/index.md b/sliding-window-maximum/index.md new file mode 100644 index 0000000..bdcd880 --- /dev/null +++ b/sliding-window-maximum/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Sliding Window Maximum +date: 2015-07-26 16:53:20+08:00 +leetcode_id: 239 +--- +{% include_relative README.md %} From d0a37287582769fda95d5579248a4aa305d09530 Mon Sep 17 00:00:00 2001 From: tgic Date: Sun, 26 Jul 2015 17:24:13 +0800 Subject: [PATCH 176/195] add product of array --- product-of-array-except-self/README.md | 0 product-of-array-except-self/Solution.java | 25 ++++++++++++++++++++++ product-of-array-except-self/index.md | 7 ++++++ 3 files changed, 32 insertions(+) create mode 100644 product-of-array-except-self/README.md create mode 100644 product-of-array-except-self/Solution.java create mode 100644 product-of-array-except-self/index.md diff --git a/product-of-array-except-self/README.md b/product-of-array-except-self/README.md new file mode 100644 index 0000000..e69de29 diff --git a/product-of-array-except-self/Solution.java b/product-of-array-except-self/Solution.java new file mode 100644 index 0000000..6a04e4a --- /dev/null +++ b/product-of-array-except-self/Solution.java @@ -0,0 +1,25 @@ +public class Solution { + public int[] productExceptSelf(int[] nums) { + int[] output = new int[nums.length]; + + if(nums.length == 0) return output; + + output[0] = nums[0]; + + for(int i = 1; i < nums.length; i++){ + output[i] = output[i - 1] * nums[i]; + } + + output[nums.length - 1] = output[nums.length - 2] * 1; + + int t = nums[nums.length - 1]; + for(int i = output.length - 2; i > 0 ; i--){ + output[i] = t * output[i - 1]; + t *= nums[i]; + } + + output[0] = t; + + return output; + } +} diff --git a/product-of-array-except-self/index.md b/product-of-array-except-self/index.md new file mode 100644 index 0000000..f20523b --- /dev/null +++ b/product-of-array-except-self/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Product of Array Except Self +date: 2015-07-26 17:23:07+08:00 +leetcode_id: 238 +--- +{% include_relative README.md %} From 4efb32f594c72fb9d70554bfc71ded6a2228e9f6 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 29 Jul 2015 18:05:42 +0800 Subject: [PATCH 177/195] Update README.md --- kth-largest-element-in-an-array/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/kth-largest-element-in-an-array/README.md b/kth-largest-element-in-an-array/README.md index e69de29..0163a90 100644 --- a/kth-largest-element-in-an-array/README.md +++ b/kth-largest-element-in-an-array/README.md @@ -0,0 +1 @@ +[An `O(n)` solution in Guava](https://github.com/google/guava/blob/v18.0/guava/src/com/google/common/collect/Ordering.java#L666) From d3267352c2dd7a14d04167a8be294b4f767ab0f7 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 6 Aug 2015 22:29:20 +0800 Subject: [PATCH 178/195] add new codes --- count-univalue-subtrees/README.md | 0 count-univalue-subtrees/Solution.java | 41 ++++++++++ count-univalue-subtrees/index.md | 7 ++ different-ways-to-add-parentheses/README.md | 0 .../Solution.java | 81 +++++++++++++++++++ different-ways-to-add-parentheses/index.md | 7 ++ flatten-2d-vector/README.md | 0 flatten-2d-vector/Solution.java | 33 ++++++++ flatten-2d-vector/Vector2D.java | 1 + flatten-2d-vector/index.md | 7 ++ strobogrammatic-number/README.md | 0 strobogrammatic-number/Solution.java | 33 ++++++++ strobogrammatic-number/index.md | 7 ++ valid-anagram/README.md | 0 valid-anagram/Solution.java | 11 +++ valid-anagram/index.md | 7 ++ 16 files changed, 235 insertions(+) create mode 100644 count-univalue-subtrees/README.md create mode 100644 count-univalue-subtrees/Solution.java create mode 100644 count-univalue-subtrees/index.md create mode 100644 different-ways-to-add-parentheses/README.md create mode 100644 different-ways-to-add-parentheses/Solution.java create mode 100644 different-ways-to-add-parentheses/index.md create mode 100644 flatten-2d-vector/README.md create mode 100644 flatten-2d-vector/Solution.java create mode 120000 flatten-2d-vector/Vector2D.java create mode 100644 flatten-2d-vector/index.md create mode 100644 strobogrammatic-number/README.md create mode 100644 strobogrammatic-number/Solution.java create mode 100644 strobogrammatic-number/index.md create mode 100644 valid-anagram/README.md create mode 100644 valid-anagram/Solution.java create mode 100644 valid-anagram/index.md diff --git a/count-univalue-subtrees/README.md b/count-univalue-subtrees/README.md new file mode 100644 index 0000000..e69de29 diff --git a/count-univalue-subtrees/Solution.java b/count-univalue-subtrees/Solution.java new file mode 100644 index 0000000..d55e7ef --- /dev/null +++ b/count-univalue-subtrees/Solution.java @@ -0,0 +1,41 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +import java.util.Objects; // remove after leetcode support import this by default + +public class Solution { + + void patch(Integer[] v, TreeNode parent, TreeNode me){ + if(me == null){ + v[1] = parent.val; + } + } + + // [count, uniq val] + Integer[] _countUnivalSubtrees(TreeNode root) { + + if(root == null) return new Integer[]{0, null}; + + Integer[] left = _countUnivalSubtrees(root.left); + patch(left, root, root.left); + + Integer[] right = _countUnivalSubtrees(root.right); + patch(right, root, root.right); + + if(Objects.equals(left[1], root.val) && Objects.equals(right[1], root.val)){ + return new Integer[]{left[0] + right[0] + 1, root.val}; + } + + return new Integer[]{left[0] + right[0], null}; + } + + public int countUnivalSubtrees(TreeNode root) { + return _countUnivalSubtrees(root)[0]; + } +} diff --git a/count-univalue-subtrees/index.md b/count-univalue-subtrees/index.md new file mode 100644 index 0000000..be868a9 --- /dev/null +++ b/count-univalue-subtrees/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Count Univalue Subtrees +date: 2015-08-06 22:25:20+08:00 +leetcode_id: 250 +--- +{% include_relative README.md %} diff --git a/different-ways-to-add-parentheses/README.md b/different-ways-to-add-parentheses/README.md new file mode 100644 index 0000000..e69de29 diff --git a/different-ways-to-add-parentheses/Solution.java b/different-ways-to-add-parentheses/Solution.java new file mode 100644 index 0000000..b1ace31 --- /dev/null +++ b/different-ways-to-add-parentheses/Solution.java @@ -0,0 +1,81 @@ +public class Solution { + + int calc(int l, int r, char op){ + switch(op){ + case '+': + return l + r; + case '-': + return l - r; + case '*': + return l * r; + } + + // unreachable + throw new RuntimeException(); + } + + List merge(Listleft, List right, char op){ + if(left.isEmpty()) return right; + if(right.isEmpty()) return left; + + List rt = new ArrayList<>(); + + for(int l : left){ + for(int r : right){ + rt.add(calc(l, r, op)); + } + } + + return rt; + } + + List diffWaysToCompute(Integer[] nums, int nst, int ned, Character[] ops){ + + List rt = new ArrayList<>(); + + if(nst + 1 == ned){ + rt.add(nums[nst]); + return rt; + } + + for(int i = nst; i < ned - 1; i++){ + char op = ops[i]; + List left = diffWaysToCompute(nums, nst, i + 1, ops); + List right = diffWaysToCompute(nums, i + 1, ned, ops); + + rt.addAll(merge(left, right, op)); + } + + return rt; + } + + public List diffWaysToCompute(String input) { + Scanner scanner = new Scanner(input); + scanner.useDelimiter(""); + + List nums = new ArrayList<>(); + List ops = new ArrayList<>(); + + while(scanner.hasNext()){ + boolean num = false; + int buf = 0; + while (scanner.hasNextInt()){ + num = true; + buf = buf * 10 + scanner.nextInt(); + } + + if(num){ + nums.add(buf); + continue; + } + + Character op = scanner.next().charAt(0); + ops.add(op); + } + + Integer[] _nums = nums.toArray(new Integer[0]); + Character[] _ops = ops.toArray(new Character[0]); + + return diffWaysToCompute(_nums, 0, _nums.length, _ops); + } +} diff --git a/different-ways-to-add-parentheses/index.md b/different-ways-to-add-parentheses/index.md new file mode 100644 index 0000000..e49e354 --- /dev/null +++ b/different-ways-to-add-parentheses/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Different Ways to Add Parentheses +date: 2015-08-06 22:21:28+08:00 +leetcode_id: 241 +--- +{% include_relative README.md %} diff --git a/flatten-2d-vector/README.md b/flatten-2d-vector/README.md new file mode 100644 index 0000000..e69de29 diff --git a/flatten-2d-vector/Solution.java b/flatten-2d-vector/Solution.java new file mode 100644 index 0000000..9422eeb --- /dev/null +++ b/flatten-2d-vector/Solution.java @@ -0,0 +1,33 @@ +public class Vector2D { + + Iterator> outterIter; + Iterator innerIter = Collections.emptyIterator(); + + public Vector2D(List> vec2d) { + outterIter = vec2d.iterator(); + } + + public int next() { + return innerIter.next(); + } + + public boolean hasNext() { + if(innerIter.hasNext()){ + return true; + } + + if(!outterIter.hasNext()){ + return false; + } + + innerIter = outterIter.next().iterator(); + + return hasNext(); + } +} + +/** + * Your Vector2D object will be instantiated and called as such: + * Vector2D i = new Vector2D(vec2d); + * while (i.hasNext()) v[f()] = i.next(); + */ diff --git a/flatten-2d-vector/Vector2D.java b/flatten-2d-vector/Vector2D.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/flatten-2d-vector/Vector2D.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/flatten-2d-vector/index.md b/flatten-2d-vector/index.md new file mode 100644 index 0000000..e08838a --- /dev/null +++ b/flatten-2d-vector/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Flatten 2D Vector +date: 2015-08-06 22:27:26+08:00 +leetcode_id: 251 +--- +{% include_relative README.md %} diff --git a/strobogrammatic-number/README.md b/strobogrammatic-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/strobogrammatic-number/Solution.java b/strobogrammatic-number/Solution.java new file mode 100644 index 0000000..b3fea63 --- /dev/null +++ b/strobogrammatic-number/Solution.java @@ -0,0 +1,33 @@ +public class Solution { + + static final char[][] GOOD_PATTERNS = { + {'9', '6'}, + {'6', '9'}, + {'1', '1'}, + {'8', '8'}, + {'0', '0'}, + }; + + boolean isStrobogrammatic(char l, char r){ + char[] s = new char[]{l, r}; + + for(char[] g : GOOD_PATTERNS){ + if(Arrays.equals(g, s)){ + return true; + } + } + return false; + } + + public boolean isStrobogrammatic(String num) { + char[] S = num.toCharArray(); + + for(int i = 0; i <= S.length / 2; i++){ + if(!isStrobogrammatic(S[i], S[S.length - 1 - i])){ + return false; + } + } + + return true; + } +} diff --git a/strobogrammatic-number/index.md b/strobogrammatic-number/index.md new file mode 100644 index 0000000..36a151a --- /dev/null +++ b/strobogrammatic-number/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Strobogrammatic Number +date: 2015-08-06 22:24:30+08:00 +leetcode_id: 246 +--- +{% include_relative README.md %} diff --git a/valid-anagram/README.md b/valid-anagram/README.md new file mode 100644 index 0000000..e69de29 diff --git a/valid-anagram/Solution.java b/valid-anagram/Solution.java new file mode 100644 index 0000000..5e64451 --- /dev/null +++ b/valid-anagram/Solution.java @@ -0,0 +1,11 @@ +public class Solution { + public boolean isAnagram(String s, String t) { + char[] S = s.toCharArray(); + char[] T = t.toCharArray(); + + Arrays.sort(S); + Arrays.sort(T); + + return Arrays.equals(S, T); + } +} diff --git a/valid-anagram/index.md b/valid-anagram/index.md new file mode 100644 index 0000000..cec6d9b --- /dev/null +++ b/valid-anagram/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Valid Anagram +date: 2015-08-06 22:22:20+08:00 +leetcode_id: 242 +--- +{% include_relative README.md %} From 743d3af40316906bdf4135d02dfb8dbd8054ce12 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 12 Aug 2015 20:04:52 +0800 Subject: [PATCH 179/195] add meeting roooms --- meeting-rooms-ii/README.md | 0 meeting-rooms-ii/Solution.java | 46 ++++++++++++++++++++++++++++++++++ meeting-rooms-ii/index.md | 7 ++++++ meeting-rooms/README.md | 0 meeting-rooms/Solution.java | 26 +++++++++++++++++++ meeting-rooms/index.md | 7 ++++++ 6 files changed, 86 insertions(+) create mode 100644 meeting-rooms-ii/README.md create mode 100644 meeting-rooms-ii/Solution.java create mode 100644 meeting-rooms-ii/index.md create mode 100644 meeting-rooms/README.md create mode 100644 meeting-rooms/Solution.java create mode 100644 meeting-rooms/index.md diff --git a/meeting-rooms-ii/README.md b/meeting-rooms-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/meeting-rooms-ii/Solution.java b/meeting-rooms-ii/Solution.java new file mode 100644 index 0000000..7f00416 --- /dev/null +++ b/meeting-rooms-ii/Solution.java @@ -0,0 +1,46 @@ +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + + static class RoomAllocator { + + List rooms = new ArrayList<>(); + + int currentTime = -1; + + void alloc(Interval room){ + for(int i = 0; i < rooms.size(); i++){ + if(rooms.get(i).end <= currentTime){ + rooms.set(i, room); + return; + } + } + + rooms.add(room); + } + + void freeBefore(int time){ + currentTime = time; + } + } + + public int minMeetingRooms(Interval[] intervals) { + Arrays.sort(intervals, (a, b) -> a.start - b.start); + + RoomAllocator ra = new RoomAllocator(); + + for(Interval i : intervals){ + ra.freeBefore(i.start); + ra.alloc(i); + } + + return ra.rooms.size(); + } +} diff --git a/meeting-rooms-ii/index.md b/meeting-rooms-ii/index.md new file mode 100644 index 0000000..cf55133 --- /dev/null +++ b/meeting-rooms-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Meeting Rooms II +date: 2015-08-12 20:03:46+08:00 +leetcode_id: 253 +--- +{% include_relative README.md %} diff --git a/meeting-rooms/README.md b/meeting-rooms/README.md new file mode 100644 index 0000000..e69de29 diff --git a/meeting-rooms/Solution.java b/meeting-rooms/Solution.java new file mode 100644 index 0000000..c7d0eba --- /dev/null +++ b/meeting-rooms/Solution.java @@ -0,0 +1,26 @@ +/** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ +public class Solution { + public boolean canAttendMeetings(Interval[] intervals) { + Arrays.sort(intervals, (a, b) -> a.start - b.start); + + int maxend = 0; + + for(Interval i : intervals){ + if(i.start < maxend){ + return false; + } + + maxend = Math.max(maxend, i.end); + } + + return true; + } +} diff --git a/meeting-rooms/index.md b/meeting-rooms/index.md new file mode 100644 index 0000000..3b7e736 --- /dev/null +++ b/meeting-rooms/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Meeting Rooms +date: 2015-08-12 20:02:37+08:00 +leetcode_id: 252 +--- +{% include_relative README.md %} From 21543312322172c9e2725778e9e5a52e642be83c Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 12 Aug 2015 23:05:38 +0800 Subject: [PATCH 180/195] add factor comb --- factor-combinations/README.md | 0 factor-combinations/Solution.java | 26 ++++++++++++++++++++++++++ factor-combinations/index.md | 7 +++++++ 3 files changed, 33 insertions(+) create mode 100644 factor-combinations/README.md create mode 100644 factor-combinations/Solution.java create mode 100644 factor-combinations/index.md diff --git a/factor-combinations/README.md b/factor-combinations/README.md new file mode 100644 index 0000000..e69de29 diff --git a/factor-combinations/Solution.java b/factor-combinations/Solution.java new file mode 100644 index 0000000..05a8d9d --- /dev/null +++ b/factor-combinations/Solution.java @@ -0,0 +1,26 @@ +public class Solution { + List> getFactors(int n, int low, int high) { + List> found = new ArrayList<>(); + + if(low <= n && n < high){ + found.add(Arrays.asList(n)); + } + + for(int i = low; n / i >= low; i++){ + if(n % i == 0){ + for(List sub : getFactors(n / i, i, n)){ + List l = new ArrayList<>(); + l.add(i); + l.addAll(sub); + found.add(l); + } + } + } + + return found; + } + + public List> getFactors(int n) { + return getFactors(n, 2, n); + } +} diff --git a/factor-combinations/index.md b/factor-combinations/index.md new file mode 100644 index 0000000..0d45107 --- /dev/null +++ b/factor-combinations/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Factor Combinations +date: 2015-08-12 23:03:42+08:00 +leetcode_id: 254 +--- +{% include_relative README.md %} From 586de58fd85c3c7ae252a25f21d6e1112edc6ce3 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 17 Aug 2015 00:37:12 +0800 Subject: [PATCH 181/195] add 4 new codes --- add-digits/README.md | 0 add-digits/Solution.java | 5 +++ add-digits/index.md | 7 +++ binary-tree-paths/README.md | 0 binary-tree-paths/Solution.java | 38 ++++++++++++++++ binary-tree-paths/index.md | 7 +++ paint-house/README.md | 0 paint-house/Solution.java | 45 +++++++++++++++++++ paint-house/index.md | 7 +++ .../README.md | 0 .../Solution.java | 31 +++++++++++++ .../index.md | 7 +++ 12 files changed, 147 insertions(+) create mode 100644 add-digits/README.md create mode 100644 add-digits/Solution.java create mode 100644 add-digits/index.md create mode 100644 binary-tree-paths/README.md create mode 100644 binary-tree-paths/Solution.java create mode 100644 binary-tree-paths/index.md create mode 100644 paint-house/README.md create mode 100644 paint-house/Solution.java create mode 100644 paint-house/index.md create mode 100644 verify-preorder-sequence-in-binary-search-tree/README.md create mode 100644 verify-preorder-sequence-in-binary-search-tree/Solution.java create mode 100644 verify-preorder-sequence-in-binary-search-tree/index.md diff --git a/add-digits/README.md b/add-digits/README.md new file mode 100644 index 0000000..e69de29 diff --git a/add-digits/Solution.java b/add-digits/Solution.java new file mode 100644 index 0000000..ef36b1f --- /dev/null +++ b/add-digits/Solution.java @@ -0,0 +1,5 @@ +public class Solution { + public int addDigits(int num) { + return num - (num - 1) / 9 * 9; + } +} diff --git a/add-digits/index.md b/add-digits/index.md new file mode 100644 index 0000000..0842b3f --- /dev/null +++ b/add-digits/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Add Digits +date: 2015-08-17 00:35:59+08:00 +leetcode_id: 258 +--- +{% include_relative README.md %} diff --git a/binary-tree-paths/README.md b/binary-tree-paths/README.md new file mode 100644 index 0000000..e69de29 diff --git a/binary-tree-paths/Solution.java b/binary-tree-paths/Solution.java new file mode 100644 index 0000000..7cbeaa5 --- /dev/null +++ b/binary-tree-paths/Solution.java @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + List merge(int v, List subPath){ + return subPath.stream() + .map(p -> v + "->" + p) + .collect(Collectors.toList()); + } + + public List binaryTreePaths(TreeNode root) { + List path = new ArrayList<>(); + + if(root == null) return path; + + if(root.left == null && root.right == null) { + // leaf + return Arrays.asList("" + root.val); + } + + if(root.left != null){ + path.addAll(merge(root.val, binaryTreePaths(root.left))); + } + + if(root.right != null) { + path.addAll(merge(root.val, binaryTreePaths(root.right))); + } + + return path; + } +} diff --git a/binary-tree-paths/index.md b/binary-tree-paths/index.md new file mode 100644 index 0000000..d6d8bae --- /dev/null +++ b/binary-tree-paths/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Binary Tree Paths +date: 2015-08-16 23:34:16+08:00 +leetcode_id: 257 +--- +{% include_relative README.md %} diff --git a/paint-house/README.md b/paint-house/README.md new file mode 100644 index 0000000..e69de29 diff --git a/paint-house/Solution.java b/paint-house/Solution.java new file mode 100644 index 0000000..9cb1899 --- /dev/null +++ b/paint-house/Solution.java @@ -0,0 +1,45 @@ +public class Solution { + static final int RED = 0b001; + static final int BLUE = 0b010; + static final int GREEN = 0b100; + + static final int NONE = 0b000; + static final int ALL = 0b111; + + static final int[] COLORS = {RED, BLUE, GREEN}; + + int index(int color){ + return color / 2; + } + + int min(int[] costs, int exclude){ + int includes = ~(ALL & exclude); + + int min = Integer.MAX_VALUE; + for(int c : COLORS){ + if((c & includes) == c){ + min = Math.min(costs[index(c)], min); + } + } + + return min; + } + + public int minCost(int[][] costs) { + if(costs.length == 0) return 0; + + int[][] minCosts = new int[costs.length][COLORS.length]; + + for(int c : COLORS){ + minCosts[0][index(c)] = costs[0][index(c)]; + } + + for(int i = 1; i < costs.length; i++){ + for(int c : COLORS){ + minCosts[i][index(c)] = costs[i][index(c)] + min(minCosts[i - 1], c); + } + } + + return min(minCosts[costs.length - 1], NONE); + } +} diff --git a/paint-house/index.md b/paint-house/index.md new file mode 100644 index 0000000..37be63b --- /dev/null +++ b/paint-house/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Paint House +date: 2015-08-17 00:33:10+08:00 +leetcode_id: 256 +--- +{% include_relative README.md %} diff --git a/verify-preorder-sequence-in-binary-search-tree/README.md b/verify-preorder-sequence-in-binary-search-tree/README.md new file mode 100644 index 0000000..e69de29 diff --git a/verify-preorder-sequence-in-binary-search-tree/Solution.java b/verify-preorder-sequence-in-binary-search-tree/Solution.java new file mode 100644 index 0000000..5ff0cb8 --- /dev/null +++ b/verify-preorder-sequence-in-binary-search-tree/Solution.java @@ -0,0 +1,31 @@ +public class Solution { + public boolean verifyPreorder(int[] preorder) { + int[] inorder = Arrays.copyOf(preorder, preorder.length); + Arrays.sort(inorder); + + LinkedList stack = new LinkedList<>(); // fuck + + stack.push(0); + stack.push(inorder.length); + + for(int p = 0; p < preorder.length; /*void*/){ + int ed = stack.pop(); + int st = stack.pop(); + + if(st >= ed) continue; + + int root = preorder[p++]; + + int i = Arrays.binarySearch(inorder, st, ed, root); + if(i < 0) return false; + + stack.push(i + 1); + stack.push(ed); + + stack.push(st); + stack.push(i); + } + + return true; + } +} diff --git a/verify-preorder-sequence-in-binary-search-tree/index.md b/verify-preorder-sequence-in-binary-search-tree/index.md new file mode 100644 index 0000000..222f175 --- /dev/null +++ b/verify-preorder-sequence-in-binary-search-tree/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: verify-preorder-sequence-in-binary-search-tree/ +date: 2015-08-15 11:47:30+08:00 +leetcode_id: 255 +--- +{% include_relative README.md %} From 3df4933955319ab0728151fd3db908ef8b07d39a Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 17 Aug 2015 15:11:18 +0800 Subject: [PATCH 182/195] remove import java.util.Objects --- count-univalue-subtrees/Solution.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/count-univalue-subtrees/Solution.java b/count-univalue-subtrees/Solution.java index d55e7ef..53c86e4 100644 --- a/count-univalue-subtrees/Solution.java +++ b/count-univalue-subtrees/Solution.java @@ -7,8 +7,6 @@ * TreeNode(int x) { val = x; } * } */ -import java.util.Objects; // remove after leetcode support import this by default - public class Solution { void patch(Integer[] v, TreeNode parent, TreeNode me){ From 927c01bcbea24433fcc7de2277cb293372600bc4 Mon Sep 17 00:00:00 2001 From: tgic Date: Wed, 19 Aug 2015 22:58:07 +0800 Subject: [PATCH 183/195] Update index.md --- verify-preorder-sequence-in-binary-search-tree/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/verify-preorder-sequence-in-binary-search-tree/index.md b/verify-preorder-sequence-in-binary-search-tree/index.md index 222f175..48b4017 100644 --- a/verify-preorder-sequence-in-binary-search-tree/index.md +++ b/verify-preorder-sequence-in-binary-search-tree/index.md @@ -1,6 +1,6 @@ --- layout: solution -title: verify-preorder-sequence-in-binary-search-tree/ +title: Verify Preorder Sequence in Binary Search Tree date: 2015-08-15 11:47:30+08:00 leetcode_id: 255 --- From 0999280a4eb6b1fb0975cb719105ab2f5462a63c Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 24 Aug 2015 12:57:04 +0800 Subject: [PATCH 184/195] smarter skeleton.sh --- skeleton.sh | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/skeleton.sh b/skeleton.sh index fa3c0c7..9cf62c8 100755 --- a/skeleton.sh +++ b/skeleton.sh @@ -7,6 +7,11 @@ if [ -z "$leetcode_name" ]; then exit; fi +info=`curl -s https://leetcode.com/problemset/algorithms/ | grep missing-number -B 2` +IFS= +leetcode_id=`(sed 's/\\(.*\\)<\\/td>/\\1/' | sed 's/^ *//') < <(echo $info | head -n 1)` +title=`(sed 's/\\(.*\\)<\\/a>/\\1/' | sed 's/^ *//') < <(echo $info | tail -n 1)` + now=`date --rfc-3339=seconds` mkdir -p $leetcode_name @@ -16,9 +21,9 @@ mkdir -p $leetcode_name cat > $leetcode_name/index.md < Date: Mon, 24 Aug 2015 12:57:22 +0800 Subject: [PATCH 185/195] too old to catch up with leetcode --- missing-number/README.md | 0 missing-number/Solution.java | 36 ++++++++++++++++++++++++++++ missing-number/index.md | 7 ++++++ shortest-word-distance/README.md | 0 shortest-word-distance/Solution.java | 23 ++++++++++++++++++ shortest-word-distance/index.md | 7 ++++++ 6 files changed, 73 insertions(+) create mode 100644 missing-number/README.md create mode 100644 missing-number/Solution.java create mode 100644 missing-number/index.md create mode 100644 shortest-word-distance/README.md create mode 100644 shortest-word-distance/Solution.java create mode 100644 shortest-word-distance/index.md diff --git a/missing-number/README.md b/missing-number/README.md new file mode 100644 index 0000000..e69de29 diff --git a/missing-number/Solution.java b/missing-number/Solution.java new file mode 100644 index 0000000..6d7e053 --- /dev/null +++ b/missing-number/Solution.java @@ -0,0 +1,36 @@ +public class Solution { + + void swap(int[] nums, int i, int j){ + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + + void sort(int[] nums){ + + for(int i = 0; i < nums.length; i++){ + while(nums[i] != i){ + if(nums[i] < 0) break; + + if(nums[i] >= nums.length) { + nums[i] = -1; + break; // drop + } + + swap(nums, nums[i], i); + } + } + } + + public int missingNumber(int[] nums) { + sort(nums); + + for(int i = 0; i < nums.length; i++){ + if(nums[i] != i){ + return i; + } + } + + return nums.length; + } +} diff --git a/missing-number/index.md b/missing-number/index.md new file mode 100644 index 0000000..8ec826c --- /dev/null +++ b/missing-number/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Missing Number +date: 2015-08-24 12:56:25+08:00 +leetcode_id: 268 +--- +{% include_relative README.md %} diff --git a/shortest-word-distance/README.md b/shortest-word-distance/README.md new file mode 100644 index 0000000..e69de29 diff --git a/shortest-word-distance/Solution.java b/shortest-word-distance/Solution.java new file mode 100644 index 0000000..2510f2e --- /dev/null +++ b/shortest-word-distance/Solution.java @@ -0,0 +1,23 @@ +public class Solution { + public int shortestDistance(String[] words, String word1, String word2) { + + int len = words.length; + + int i1 = -1; + int i2 = -1; + + for(int i = 0; i < words.length; i++){ + if(word1.equals(words[i])){ + i1 = i; + }else if(word2.equals(words[i])){ + i2 = i; + } + + if(i1 >= 0 && i2 >= 0){ + len = Math.min(len, Math.abs(i1 - i2)); + } + } + + return len; + } +} diff --git a/shortest-word-distance/index.md b/shortest-word-distance/index.md new file mode 100644 index 0000000..93c70ba --- /dev/null +++ b/shortest-word-distance/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Shortest Word Distance +date: 2015-08-17 01:11:54+08:00 +leetcode_id: 243 +--- +{% include_relative README.md %} From 9b8ff3cea9df412882f1686dd0c1bb6a8f77ce20 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 24 Aug 2015 17:23:01 +0800 Subject: [PATCH 186/195] fix typo --- skeleton.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skeleton.sh b/skeleton.sh index 9cf62c8..740d609 100755 --- a/skeleton.sh +++ b/skeleton.sh @@ -7,7 +7,7 @@ if [ -z "$leetcode_name" ]; then exit; fi -info=`curl -s https://leetcode.com/problemset/algorithms/ | grep missing-number -B 2` +info=`curl -s https://leetcode.com/problemset/algorithms/ | grep $leetcode_name -B 2` IFS= leetcode_id=`(sed 's/\\(.*\\)<\\/td>/\\1/' | sed 's/^ *//') < <(echo $info | head -n 1)` title=`(sed 's/\\(.*\\)<\\/a>/\\1/' | sed 's/^ *//') < <(echo $info | tail -n 1)` From eef54108e6fc90202ca3e89727288ee51bcc2de3 Mon Sep 17 00:00:00 2001 From: tgic Date: Mon, 24 Aug 2015 17:23:17 +0800 Subject: [PATCH 187/195] add easy one and test skeleton.sh --- palindrome-permutation/README.md | 3 +++ palindrome-permutation/Solution.java | 29 ++++++++++++++++++++++++++++ palindrome-permutation/index.md | 7 +++++++ 3 files changed, 39 insertions(+) create mode 100644 palindrome-permutation/README.md create mode 100644 palindrome-permutation/Solution.java create mode 100644 palindrome-permutation/index.md diff --git a/palindrome-permutation/README.md b/palindrome-permutation/README.md new file mode 100644 index 0000000..6d48e7a --- /dev/null +++ b/palindrome-permutation/README.md @@ -0,0 +1,3 @@ +## Counting Map + + diff --git a/palindrome-permutation/Solution.java b/palindrome-permutation/Solution.java new file mode 100644 index 0000000..68e78bb --- /dev/null +++ b/palindrome-permutation/Solution.java @@ -0,0 +1,29 @@ +public class Solution { + public boolean canPermutePalindrome(String s) { + Map m = new HashMap<>(); + + for(char c : s.toCharArray()){ + Integer i = m.get(c); + + if(i == null){ + m.put(c, 1); + } else { + m.put(c, i + 1); + } + } + + int single = 0; + + for(int v : m.values()){ + if(v % 2 == 1){ + single++; + } + + if(single > 1){ + return false; + } + } + + return true; + } +} diff --git a/palindrome-permutation/index.md b/palindrome-permutation/index.md new file mode 100644 index 0000000..9444ba2 --- /dev/null +++ b/palindrome-permutation/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Palindrome Permutation +date: 2015-08-24 17:21:42+08:00 +leetcode_id: 267 +--- +{% include_relative README.md %} From f7b2711146f2e8932a0e1d22049ac5f4e207b9f5 Mon Sep 17 00:00:00 2001 From: tgic Date: Tue, 25 Aug 2015 01:07:29 +0800 Subject: [PATCH 188/195] add pla permutation ii and single num iii --- palindrome-permutation-ii/README.md | 0 palindrome-permutation-ii/Solution.java | 58 +++++++++++++++++++++++++ palindrome-permutation-ii/index.md | 7 +++ single-number-iii/README.md | 0 single-number-iii/Solution.java | 21 +++++++++ single-number-iii/index.md | 7 +++ 6 files changed, 93 insertions(+) create mode 100644 palindrome-permutation-ii/README.md create mode 100644 palindrome-permutation-ii/Solution.java create mode 100644 palindrome-permutation-ii/index.md create mode 100644 single-number-iii/README.md create mode 100644 single-number-iii/Solution.java create mode 100644 single-number-iii/index.md diff --git a/palindrome-permutation-ii/README.md b/palindrome-permutation-ii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/palindrome-permutation-ii/Solution.java b/palindrome-permutation-ii/Solution.java new file mode 100644 index 0000000..e62df14 --- /dev/null +++ b/palindrome-permutation-ii/Solution.java @@ -0,0 +1,58 @@ +public class Solution { + Set permute(ArrayList chars, final String single){ + + if(chars.isEmpty()){ + + return Collections.singleton(single); + } else if(chars.size() == 1) { + + return Collections.singleton(chars.get(0) + single + chars.get(0)); + } + + Set found = new HashSet<>(); + + // else + for(int i = 0; i < chars.size(); i++){ + + char c = chars.get(i); + + ArrayList rest = new ArrayList<>(chars); + rest.remove(i); + + found.addAll(permute(rest, single).stream() + .map(s -> c + s + c) + .collect(Collectors.toSet())); + } + + return found; + } + + public List generatePalindromes(String s) { + + + ArrayList chars = new ArrayList<>(); + + Set single = new HashSet<>(); + + for(char c : s.toCharArray()){ + + if(single.contains(c)){ + single.remove(c); + chars.add(c); + } else { + single.add(c); + } + } + + if(single.size() > 1) return Collections.emptyList(); + + // else + String _single = ""; + + if(single.size() == 1) { + _single = single.iterator().next() + ""; + } + + return new ArrayList<>(permute(chars, _single)); + } +} diff --git a/palindrome-permutation-ii/index.md b/palindrome-permutation-ii/index.md new file mode 100644 index 0000000..aba642c --- /dev/null +++ b/palindrome-permutation-ii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Palindrome Permutation II +date: 2015-08-25 00:48:04+08:00 +leetcode_id: 267 +--- +{% include_relative README.md %} diff --git a/single-number-iii/README.md b/single-number-iii/README.md new file mode 100644 index 0000000..e69de29 diff --git a/single-number-iii/Solution.java b/single-number-iii/Solution.java new file mode 100644 index 0000000..0d6ea7e --- /dev/null +++ b/single-number-iii/Solution.java @@ -0,0 +1,21 @@ +public class Solution { + public int[] singleNumber(int[] nums) { + int aXORb = nums[0]; + + for(int i = 1; i < nums.length; i++){ + aXORb ^= nums[i]; + } + + // this bit either in a or b + int bit = Integer.lowestOneBit(aXORb); + + int a = 0; + for(int n : nums){ + if((n & bit) == bit){ + a ^= n; + } + } + + return new int[]{a, aXORb ^ a}; + } +} diff --git a/single-number-iii/index.md b/single-number-iii/index.md new file mode 100644 index 0000000..669d318 --- /dev/null +++ b/single-number-iii/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Single Number III +date: 2015-08-25 00:56:56+08:00 +leetcode_id: 260 +--- +{% include_relative README.md %} From d63fdbd955da876c944471588f31ec7aa4c2ea84 Mon Sep 17 00:00:00 2001 From: tgic Date: Fri, 28 Aug 2015 16:23:41 +0800 Subject: [PATCH 189/195] add closeset bst value --- closest-binary-search-tree-value/README.md | 0 .../Solution.java | 34 +++++++++++++++++++ closest-binary-search-tree-value/index.md | 7 ++++ 3 files changed, 41 insertions(+) create mode 100644 closest-binary-search-tree-value/README.md create mode 100644 closest-binary-search-tree-value/Solution.java create mode 100644 closest-binary-search-tree-value/index.md diff --git a/closest-binary-search-tree-value/README.md b/closest-binary-search-tree-value/README.md new file mode 100644 index 0000000..e69de29 diff --git a/closest-binary-search-tree-value/Solution.java b/closest-binary-search-tree-value/Solution.java new file mode 100644 index 0000000..4408944 --- /dev/null +++ b/closest-binary-search-tree-value/Solution.java @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + int closestValue(int v1, int v2, double target){ + double _v1 = Math.abs(target - v1); + double _v2 = Math.abs(target - v2); + + if(_v1 < _v2) return v1; + else return v2; + } + + public int closestValue(TreeNode root, double target) { + + int closest = root.val; + + if(root.left != null){ + closest = closestValue(closestValue(root.left, target), closest, target); + } + + if(root.right != null){ + closest = closestValue(closestValue(root.right, target), closest, target); + } + + return closest; + } +} diff --git a/closest-binary-search-tree-value/index.md b/closest-binary-search-tree-value/index.md new file mode 100644 index 0000000..d5e7a94 --- /dev/null +++ b/closest-binary-search-tree-value/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Closest Binary Search Tree Value +date: 2015-08-28 14:52:37+08:00 +leetcode_id: 270 +--- +{% include_relative README.md %} From 4f3a4bac33fc7ea54a7e4f72f7c312bb4bfa2ece Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 3 Sep 2015 13:33:55 +0800 Subject: [PATCH 190/195] add encode and decode strings --- encode-and-decode-strings/Codec.java | 1 + encode-and-decode-strings/README.md | 0 encode-and-decode-strings/Solution.java | 63 +++++++++++++++++++++++++ encode-and-decode-strings/index.md | 7 +++ 4 files changed, 71 insertions(+) create mode 120000 encode-and-decode-strings/Codec.java create mode 100644 encode-and-decode-strings/README.md create mode 100644 encode-and-decode-strings/Solution.java create mode 100644 encode-and-decode-strings/index.md diff --git a/encode-and-decode-strings/Codec.java b/encode-and-decode-strings/Codec.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/encode-and-decode-strings/Codec.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/encode-and-decode-strings/README.md b/encode-and-decode-strings/README.md new file mode 100644 index 0000000..e69de29 diff --git a/encode-and-decode-strings/Solution.java b/encode-and-decode-strings/Solution.java new file mode 100644 index 0000000..ae01953 --- /dev/null +++ b/encode-and-decode-strings/Solution.java @@ -0,0 +1,63 @@ +public class Codec { + + static final int MAX_LEN = Integer.toHexString(Integer.MAX_VALUE).length(); + + // lazy ... should be byte[] + static final String NUM_PATTERN = "%0" + MAX_LEN + "x"; + + String serializeNumber(int n){ + return String.format(NUM_PATTERN, n); + } + + int deserializeNumber(char[] s, int offset){ + return Integer.parseInt(new String(s, offset, MAX_LEN), 16); + } + + /* [count] [str len] [str ...] ... [str len][str ... ] + * 0 L 2L 2L + strlen nL (n + 1)L (n + 1)L + strlen + */ + + // Encodes a list of strings to a single string. + public String encode(List strs) { + StringBuilder sb = new StringBuilder(); + sb.append(serializeNumber(strs.size())); + + for(String s : strs){ + sb.append(serializeNumber(s.length())); + sb.append(s); + } + + return sb.toString(); + } + + // Decodes a single string to a list of strings. + public List decode(String s) { + char[] S = s.toCharArray(); + + int offset = 0; + int n = deserializeNumber(S, offset); + // move to first str len start + offset += MAX_LEN; + + ArrayList strs = new ArrayList<>(n); + + for(int i = 0; i < n; i++){ + + int len = deserializeNumber(S, offset); + + // move to str start + offset += MAX_LEN; + + strs.add(new String(S, offset, len)); + + // move to next str len start + offset += len; + } + + return strs; + } +} + +// Your Codec object will be instantiated and called as such: +// Codec codec = new Codec(); +// codec.decode(codec.encode(strs)); diff --git a/encode-and-decode-strings/index.md b/encode-and-decode-strings/index.md new file mode 100644 index 0000000..ac59955 --- /dev/null +++ b/encode-and-decode-strings/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Encode and Decode Strings +date: 2015-09-03 13:28:10+08:00 +leetcode_id: 271 +--- +{% include_relative README.md %} From d4e1cb63bdb34057b9dd48d3bc117cc8ccccf4f9 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 24 Sep 2015 15:56:36 +0800 Subject: [PATCH 191/195] first easy after a happy holiday --- move-zeroes/README.md | 0 move-zeroes/Solution.java | 49 +++++++++++++++++++++++++++++++++++++++ move-zeroes/index.md | 7 ++++++ 3 files changed, 56 insertions(+) create mode 100644 move-zeroes/README.md create mode 100644 move-zeroes/Solution.java create mode 100644 move-zeroes/index.md diff --git a/move-zeroes/README.md b/move-zeroes/README.md new file mode 100644 index 0000000..e69de29 diff --git a/move-zeroes/Solution.java b/move-zeroes/Solution.java new file mode 100644 index 0000000..d02e5f2 --- /dev/null +++ b/move-zeroes/Solution.java @@ -0,0 +1,49 @@ +public class Solution { + + void shiftLeft(int[] nums, int p, final int c){ + if(c <= 0) return; + + while(p < nums.length){ + nums[p - c] = nums[p]; + + if(nums[p] == 0) break; + + p++; + } + + for(int i = p - c; i < p; i++){ + nums[i] = 0; + } + } + + public void moveZeroes(int[] nums) { + + int i = nums.length - 1; + + // trim tailing zero + while(i >= 0 && nums[i] == 0) i--; + + int s = i; + + boolean metzero = false; + + while(i >= 0){ + + if(nums[i] != 0){ + + if(metzero){ + shiftLeft(nums, s, s - i - 1); + metzero = false; + } + + s = i; + } else { + metzero = true; + } + + i--; + } + + shiftLeft(nums, s, s); + } +} diff --git a/move-zeroes/index.md b/move-zeroes/index.md new file mode 100644 index 0000000..5bddd19 --- /dev/null +++ b/move-zeroes/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Move Zeroes +date: 2015-09-24 15:55:37+08:00 +leetcode_id: 283 +--- +{% include_relative README.md %} From d616bbc43fde0d356b935bf1de17e99b389c17bf Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 24 Sep 2015 17:32:52 +0800 Subject: [PATCH 192/195] stop if cant fetch leetcode_id --- skeleton.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/skeleton.sh b/skeleton.sh index 740d609..54a550e 100755 --- a/skeleton.sh +++ b/skeleton.sh @@ -7,11 +7,16 @@ if [ -z "$leetcode_name" ]; then exit; fi -info=`curl -s https://leetcode.com/problemset/algorithms/ | grep $leetcode_name -B 2` +info=`curl -s https://leetcode.com/problemset/algorithms/ | grep /$leetcode_name/ -B 2` IFS= leetcode_id=`(sed 's/\\(.*\\)<\\/td>/\\1/' | sed 's/^ *//') < <(echo $info | head -n 1)` title=`(sed 's/\\(.*\\)<\\/a>/\\1/' | sed 's/^ *//') < <(echo $info | tail -n 1)` +if [ -z "$leetcode_id" ]; then + echo "cant fetch leetcode_id for $leetcode_name" + exit +fi + now=`date --rfc-3339=seconds` mkdir -p $leetcode_name From 57ebe02dbc21f19fffdad9040fdaead5c9dd68d3 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 24 Sep 2015 17:35:09 +0800 Subject: [PATCH 193/195] add biset and next inorder bst --- first-bad-version/README.md | 0 first-bad-version/Solution.java | 23 +++++++++++++++++ first-bad-version/index.md | 7 ++++++ inorder-successor-in-bst/README.md | 0 inorder-successor-in-bst/Solution.java | 35 ++++++++++++++++++++++++++ inorder-successor-in-bst/index.md | 7 ++++++ 6 files changed, 72 insertions(+) create mode 100644 first-bad-version/README.md create mode 100644 first-bad-version/Solution.java create mode 100644 first-bad-version/index.md create mode 100644 inorder-successor-in-bst/README.md create mode 100644 inorder-successor-in-bst/Solution.java create mode 100644 inorder-successor-in-bst/index.md diff --git a/first-bad-version/README.md b/first-bad-version/README.md new file mode 100644 index 0000000..e69de29 diff --git a/first-bad-version/Solution.java b/first-bad-version/Solution.java new file mode 100644 index 0000000..9e0007b --- /dev/null +++ b/first-bad-version/Solution.java @@ -0,0 +1,23 @@ +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int good = 0; // not exists + int bad = n; + + for(;;) { + + if(bad - good <= 1) return bad; + + int t = (bad - good) / 2 + good; // fuck overflow + + if(isBadVersion(t)){ + bad = t; + } else { + good = t; + } + } + + } +} diff --git a/first-bad-version/index.md b/first-bad-version/index.md new file mode 100644 index 0000000..3620450 --- /dev/null +++ b/first-bad-version/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: First Bad Version +date: 2015-09-24 16:10:45+08:00 +leetcode_id: 278 +--- +{% include_relative README.md %} diff --git a/inorder-successor-in-bst/README.md b/inorder-successor-in-bst/README.md new file mode 100644 index 0000000..e69de29 diff --git a/inorder-successor-in-bst/Solution.java b/inorder-successor-in-bst/Solution.java new file mode 100644 index 0000000..a10605e --- /dev/null +++ b/inorder-successor-in-bst/Solution.java @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +public class Solution { + + TreeNode leftMost(TreeNode root){ + if(root == null) return null; + if(root.left != null) return leftMost(root.left); + return root; + } + + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + if(root == p) { + return leftMost(p.right); + } + + if(p.val < root.val) { + p = inorderSuccessor(root.left, p); + + if(p == null){ + return root; + } + + return p; + } + + return inorderSuccessor(root.right, p); + } +} diff --git a/inorder-successor-in-bst/index.md b/inorder-successor-in-bst/index.md new file mode 100644 index 0000000..a1a952d --- /dev/null +++ b/inorder-successor-in-bst/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Inorder Successor in BST +date: 2015-09-24 17:32:03+08:00 +leetcode_id: 285 +--- +{% include_relative README.md %} From 9f561e5b75a2090f82c846c26ec75c297396cd15 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 24 Sep 2015 17:54:43 +0800 Subject: [PATCH 194/195] add zigzag iter --- zigzag-iterator/README.md | 0 zigzag-iterator/Solution.java | 37 +++++++++++++++++++++++++++++ zigzag-iterator/ZigzagIterator.java | 1 + zigzag-iterator/index.md | 7 ++++++ 4 files changed, 45 insertions(+) create mode 100644 zigzag-iterator/README.md create mode 100644 zigzag-iterator/Solution.java create mode 120000 zigzag-iterator/ZigzagIterator.java create mode 100644 zigzag-iterator/index.md diff --git a/zigzag-iterator/README.md b/zigzag-iterator/README.md new file mode 100644 index 0000000..e69de29 diff --git a/zigzag-iterator/Solution.java b/zigzag-iterator/Solution.java new file mode 100644 index 0000000..7f04d78 --- /dev/null +++ b/zigzag-iterator/Solution.java @@ -0,0 +1,37 @@ +public class ZigzagIterator { + + Iterator[] ivs; + + int p = 0; + + public ZigzagIterator(List v1, List v2) { + ivs = new Iterator[]{v1.iterator(), v2.iterator()}; + } + + public int next() { + for(;;){ + + Iterator i = ivs[p++ % ivs.length]; + + if(i.hasNext()){ + return i.next(); + } + } + } + + public boolean hasNext() { + for(Iterator i : ivs){ + if(i.hasNext()){ + return true; + } + } + + return false; + } +} + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i = new ZigzagIterator(v1, v2); + * while (i.hasNext()) v[f()] = i.next(); + */ diff --git a/zigzag-iterator/ZigzagIterator.java b/zigzag-iterator/ZigzagIterator.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/zigzag-iterator/ZigzagIterator.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/zigzag-iterator/index.md b/zigzag-iterator/index.md new file mode 100644 index 0000000..acb4140 --- /dev/null +++ b/zigzag-iterator/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Zigzag Iterator +date: 2015-09-24 17:53:54+08:00 +leetcode_id: 281 +--- +{% include_relative README.md %} From b2b0ac5e531c3609a780990761f146ab7f267b19 Mon Sep 17 00:00:00 2001 From: tgic Date: Thu, 24 Sep 2015 18:03:03 +0800 Subject: [PATCH 195/195] add peeking iter --- peeking-iterator/PeekingIterator.java | 1 + peeking-iterator/README.md | 0 peeking-iterator/Solution.java | 44 +++++++++++++++++++++++++++ peeking-iterator/index.md | 7 +++++ 4 files changed, 52 insertions(+) create mode 120000 peeking-iterator/PeekingIterator.java create mode 100644 peeking-iterator/README.md create mode 100644 peeking-iterator/Solution.java create mode 100644 peeking-iterator/index.md diff --git a/peeking-iterator/PeekingIterator.java b/peeking-iterator/PeekingIterator.java new file mode 120000 index 0000000..e570129 --- /dev/null +++ b/peeking-iterator/PeekingIterator.java @@ -0,0 +1 @@ +Solution.java \ No newline at end of file diff --git a/peeking-iterator/README.md b/peeking-iterator/README.md new file mode 100644 index 0000000..e69de29 diff --git a/peeking-iterator/Solution.java b/peeking-iterator/Solution.java new file mode 100644 index 0000000..e3800d2 --- /dev/null +++ b/peeking-iterator/Solution.java @@ -0,0 +1,44 @@ +// Java Iterator interface reference: +// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html +class PeekingIterator implements Iterator { + + static final Integer NONE = new Integer(0); + + Iterator iterator; + + Integer next = NONE; + + public PeekingIterator(Iterator iterator) { + // initialize any member here. + this.iterator = iterator; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + if(next == NONE){ + next = iterator.next(); + } + + return next; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + if(next != NONE){ + try{ + return next; + } finally { + next = NONE; + } + } + + return iterator.next(); + } + + @Override + public boolean hasNext() { + return next != NONE || iterator.hasNext(); + } +} diff --git a/peeking-iterator/index.md b/peeking-iterator/index.md new file mode 100644 index 0000000..048d659 --- /dev/null +++ b/peeking-iterator/index.md @@ -0,0 +1,7 @@ +--- +layout: solution +title: Peeking Iterator +date: 2015-09-24 18:02:14+08:00 +leetcode_id: 284 +--- +{% include_relative README.md %}