Skip to content

Commit

Permalink
3sum profiling
Browse files Browse the repository at this point in the history
  • Loading branch information
s50600822 committed Mar 17, 2024
1 parent d188adb commit b16e2f4
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions interview_prep/algorithm/java/ide_handicapped/3sum/README.md
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 not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit b16e2f4

Please sign in to comment.