Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
it works for some test cases but not all and gives an index out of bounds, also how can I make it better
this is my code
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] answer = new int[nums.length -1];
for(int i =0; i < nums.length; i++){
if((nums[i] + nums[i+1]) == target) {
answer[0] = i;
answer[1] = i + 1;
return answer;
}
}
return answer;
}
}
So, there are quite the few issues in the algo. some of them to mention below
Let us consider below input
[3,3,7,4,6,0,3,5].
So total array length is 8 and array starts from 0 to 7
a) here with your logic you are checking the 2 consecutive numbers that add upto a given target which is not the case. We have to find 2 numbers that may be Non consecutive as well like here lets assume the target given is 13 so we have to return [2,4].
b) with your current logic, when you run the loop for target 13, definitely your logic will execute till the end. so when i=7, if you condition is checked
if((nums[7] + nums[8]) == target) {
answer[0] = 7;
answer[1] = 8;
return answer;
}
But we know that our array runs from index 0 to 7 so this will give indexArrayOutOfBound exception as 8th index doesn't exists.
Also even if you fix this solution this might not work in optimized way with timeComplexity O(n)
You can refer below solution https://github.com/DivyaJaggya/DSAPractice/blob/main/src/arrays/Find2SumForUnsortedArray.java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.