-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
70 changes: 70 additions & 0 deletions
70
interview_prep/algorithm/java/ide_handicapped/3sum/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
## fastest | ||
```java | ||
private List<List<Integer>> res; | ||
|
||
public List<List<Integer>> threeSum(int[] nums) { | ||
|
||
return new AbstractList<List<Integer>>() { | ||
public List<Integer> get(int index) { | ||
init(); | ||
return res.get(index); | ||
} | ||
|
||
public int size() { | ||
init(); | ||
return res.size(); | ||
} | ||
|
||
private void init() { | ||
if (res != null) | ||
return; | ||
Arrays.sort(nums); | ||
int l, r, sum; | ||
final Set<List<Integer>> tempRes = new HashSet<>(); | ||
for (int i = 0; i < nums.length - 2; ++i) { | ||
l = i + 1; | ||
r = nums.length - 1; | ||
while (l < r) { | ||
sum = nums[i] + nums[l] + nums[r]; | ||
if (sum == 0) | ||
tempRes.add(Arrays.asList(nums[i], nums[l], nums[r])); | ||
if (sum < 0) | ||
++l; | ||
else | ||
--r; | ||
} | ||
} | ||
res = new ArrayList<List<Integer>>(tempRes); | ||
} | ||
|
||
}; | ||
} | ||
``` | ||
|
||
|
||
## slower | ||
```java | ||
public List<List<Integer>> threeSumSlow(int[] nums) { | ||
if (nums == null || nums.length == 0) | ||
return Collections.emptyList(); | ||
Arrays.sort(nums); | ||
int l, r, sum; | ||
final Set<List<Integer>> tempRes = new HashSet<>(); | ||
for (int i = 0; i < nums.length - 2; ++i) { | ||
l = i + 1; | ||
r = nums.length - 1; | ||
while (l < r) { | ||
sum = nums[i] + nums[l] + nums[r]; | ||
if (sum == 0) | ||
tempRes.add(Arrays.asList(nums[i], nums[l], nums[r])); | ||
if (sum < 0) | ||
++l; | ||
else | ||
--r; | ||
} | ||
} | ||
return new ArrayList<List<Integer>>(tempRes); | ||
} | ||
``` | ||
|
||
![compared](./jprofiler.png) |
Binary file not shown.
Binary file added
BIN
+126 KB
interview_prep/algorithm/java/ide_handicapped/3sum/jp_snapshot/t1Slow.jps
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.