-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum2.java
More file actions
48 lines (43 loc) · 1.17 KB
/
TwoSum2.java
File metadata and controls
48 lines (43 loc) · 1.17 KB
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
package com.leetcode;
import java.util.Arrays;
/**
* @author: yhl
* @DateTime: 2019/11/13 14:22
* @Description:
*/
public class TwoSum2 {
public static void main(String[] args) {
int[] arr = {0, 0, 3, 4};
final TwoSum2 twoSum2 = new TwoSum2();
final int[] ints = twoSum2.twoSum2(arr, 7);
System.out.println(Arrays.toString(ints));
}
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
for (int j = i+1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
return new int[]{i + 1, j + 1};
}
}
}
return new int[0];
}
/**
* perfect answer
* @param numbers
* @param target
* @return
*/
public int[] twoSum2(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while (numbers[left] + numbers[right] != target) {
if(numbers[left] + numbers[right] > target){
right--;
}else {
left++;
}
}
return new int[]{left + 1, right + 1};
}
}