-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum
More file actions
51 lines (44 loc) · 1.47 KB
/
twoSum
File metadata and controls
51 lines (44 loc) · 1.47 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
49
50
51
import java.util.Arrays;
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] result = new int[2];
// Sort a copy of the array, not the original, to preserve indices
int[] original = Arrays.copyOf(nums, n);
Arrays.sort(nums);
int i = 0;
int j = n - 1;
while (i < j) {
int sum = nums[i] + nums[j];
if (sum == target) {
// Find original indices of the numbers in the unsorted array
result[0] = findIndex(original, nums[i]);
result[1] = findIndex(original, nums[j], result[0]);
break;
} else if (sum > target) {
j--;
} else {
i++;
}
}
return result;
}
// Helper method to find the index of a number in the array
private int findIndex(int[] arr, int value) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return i;
}
}
return -1; // Should never occur if input is valid
}
// Overloaded helper method to find the second occurrence of a value
private int findIndex(int[] arr, int value, int excludeIndex) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value && i != excludeIndex) {
return i;
}
}
return -1; // Should never occur if input is valid
}
}