Skip to content

Instantly share code, notes, and snippets.

@odrianoaliveira
Created March 25, 2018 23:27
Show Gist options
  • Save odrianoaliveira/3ef753a5a391edb840d75db10e04893c to your computer and use it in GitHub Desktop.
Save odrianoaliveira/3ef753a5a391edb840d75db10e04893c to your computer and use it in GitHub Desktop.
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int [][] arr = new int[n][2];
for (int i=0; i < n; i++) {
arr[i][0] = nums[i];
arr[i][1] = i;
}
Arrays.sort(arr, new java.util.Comparator<int[]>() {
public int compare(int [] a, int [] b) {
return Double.compare(a[0], b[0]);
}
});
int i = 0, j = n-1;
int[] result = new int[2];
while ( i < j ) {
if (arr[i][0] + arr[j][0] == target) {
result[0] = Math.min(arr[i][1], arr[j][1]);
result[1] = Math.max(arr[i][1], arr[j][1]);
break;
} else if ( arr[i][0] + arr[j][0] > target) {
j--;
} else {
i++;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment