Interview 150
Two Sum II
- Problem
- LC 167
- File
- interview150_LC167TwoSumII.java
- Path
- pkg5leetcode/interview150/interview150_LC167TwoSumII.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC167TwoSumII.java
- Approach
- Sorted array two pointers from both ends.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Two Sum II | LC 1675 * APPROACH: Sorted array two pointers from both ends.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC167TwoSumII {9 static int[] twoSum(int[] numbers, int target) {10 int lo = 0, hi = numbers.length - 1;11 while (lo < hi) {12 int sum = numbers[lo] + numbers[hi];13 if (sum == target) return new int[]{lo + 1, hi + 1};14 if (sum < target) lo++;15 else hi--;16 }17 return new int[]{-1, -1};18 }19 20 public static void main(String[] args) {21 check(java.util.Arrays.equals(twoSum(new int[]{2, 7, 11, 15}, 9), new int[]{1, 2}), "case1");22 check(java.util.Arrays.equals(twoSum(new int[]{2, 3, 4}, 6), new int[]{1, 3}), "case2");23 System.out.println("all tests passed");24 }25 26 static void check(boolean cond, String name) {27 if (!cond) throw new AssertionError("FAILED: " + name);28 System.out.println(" PASS " + name);29 }30}