Solution 1: time limit exceeded
Time complexity: O(n^2)
Space complexity: O(1)
Solution 2: accepted
Two-pass hashing, using Hashmap to reduce the time for each lookup to O(1).
Time complexity: O(n)
Space complexity: O(n)
|
|
Solution 3
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.
Other Notes
Creating a temporary array almost does not cost time:
1234int[] array = new int[2];array[0] = i; same as return new int[] {i, j};array[1] = j; ======>return array;Should verify the input;
- Should return null while the result is not excepted;
- Define nums.length to get a tiny gain;