Test cases
|
|
Solution 1: Accepted
This is an easy one.
|
|
Time complexity: O(n^2)
Space complexity: O(1)
Two-pass hashing, using Hashmap to reduce the time for each lookup to O(1).
Time complexity: O(n)
Space complexity: O(n)
|
|
Array Approaching
Time complexity: O(nlogn + n) (time used to sort the array should be counted)
Space complexity: O(n)
We can also use array. We order the array first and then we find the indices of the minimum (0) and the maximum (n-1), and then add these two numbers together and compare the result with the target. If the result is larget than the target, we decrement the maximum index, otherwise we increment the minimum index.
Creating a temporary array almost does not cost time:
|
|
Should verify the input;
Time: O(n^2), Space: O(n)
The look-backs lead to maximum O(n^2) time complexity.
Time: O(n), Space: O(n)
Store the previous result rather than looking back.
Interesting: change from String to StringBuilder does not bring any performance boost.
Using String
Using StringBuilder
Improved solution 1 without looking back.
Improved solution 3, replacing hashmap with array. Even faster.
Solution 1: ~70ms
Solution 2: ~20ms
Solution 3: ~10ms
Solution 4: ~4ms
|
|
|
|
Brute force, TLE with no doubt.
Time: O(n)
Space: O(1)
|
|
Double the base if we can, decrease the time complexity to approximately logn.
Time: O(logn)
Space: O(1)
|
|
DFS.
|
|
Simplified 0ms
A very readable solution with extra spaces used.
|
|
Try to make it simple and readable.
Be aware of the concepts of reference and pointer, know how Java pass values.
|
|
DFS.
|
|
temp.remove(temp.size() - 1)
. result.add(new ArrayList<Integer>(temp))
? It passes a reference rather than an object. So if we use result.add(temp)
, we will get the same temp multiple times. In addition, temp will contains no elements at the end of the recursion, so we will always get a list of []
at the end.
|
|
Alternative
|
|
DFS.
|
|
Simplified