I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
My solution to this problem would be,
public int[] twoSums(int[] unsortedNum, int target) {
int[] nums = Arrays.copyOf(unsortedNum, unsortedNum.length);
Arrays.sort(nums);
boolean isResultFound = false;
int start = 0;
int end = nums.length-1;
while(!(start > end)) {
if(nums[start]+nums[end] > target){
end--;
} else if (nums[start]+nums[end] < target){
start++;
} else if(nums[start] + nums[end] == target){
isResultFound = true;
break;
}
}
if(isResultFound){
int s = -1;
int e = -1;
for(int i = 0; i< unsortedNum.length; i++){
if(s != -1 && e != -1){
break;
}
if(s == -1 && unsortedNum[i] == nums[start]){
s = i;
} else if(e == -1 && unsortedNum[i] == nums[end]) {
e = i;
}
}
return new int[] {s,e};
}
// for element not found
return new int[]{-1,-1};
}
In the end, if you get -1, -1 as the index then you can say that elements not found which could sum to the target element.