We move the i pointer in this solution to narrow down the range of the two numbers.
Time complexity: O(n)
Space complexity: O(1)
Solution 2 (Java)
publicclassSolution { /** * @param nums: an array of Integer * @param target: an integer * @return: [num1, num2] (num1 < num2) */publicint[] twoSum7(int[] nums,int target) { target =Math.abs(target);int j =1;for (int i =0; i <nums.length; i++) { j =Math.max(j, i +1); // prevent i and j overlapwhile (j <nums.length&& nums[j] - nums[i] < target) { j++; }if (j >=nums.length) break;if (nums[j] - nums[i] == target) {// since j is always larger i, thus this orderreturnnewint[]{nums[i], nums[j]}; } }returnnewint[]{-1,-1}; }}
Notes
This solution is also the two pointers method, but we move the j pointer. We make sure that j is always larger than i, so we do not need to check for the increasing order in the final answer.