1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class Solution167 {
public static int[] twoSum1(int[] numbers, int target) { for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.length; j++) { if (target - numbers[i] == numbers[j]) { return new int[]{i+1, j+1}; } } } return new int[2]; }
public static int[] twoSum2(int[] numbers, int target) { int res[] = new int[2]; for (int i = 0; i < numbers.length; i++) { int index2 = getIndexBetween(numbers, i + 1, numbers.length -1, target - numbers[i]); if (index2 > -1) { return new int[]{i+1, index2 + 1}; } } return res; }
private static int getIndexBetween(int[] nums, int begin, int end, int target) { int mid = (begin + end) / 2; if (begin > end) return -1; if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { return getIndexBetween(nums, begin, mid -1, target); } else { return getIndexBetween(nums, mid + 1, end, target); } }
public static int[] twoSum3(int[] numbers, int target) { int res[] = new int[2]; int left = 0, right = numbers.length -1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) { return new int[]{left + 1, right + 1}; } else if (sum < target) { left += 1; } else { right -= 1; } } return res; }
}
|