Two Sum Problem on leetcode

Hi guys, I can't seem to figure out what the problem is here: class Solution { public int[] twoSum(int[] nums, int target) { int result [] = {0, 0}; List<Integer> original = new ArrayList<Integer>(); List<Integer> complement = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) { original.add(nums[i]); complement.add(target - nums[i]);
} for (int i = 0; i < nums.length; i++) {
if (complement.contains(nums[i])) { int second = complement.indexOf(nums[i]); result [0] = i; result [1] = second; }
} return result; } } It does work for 62 out of 63 test cases but gives a wrong answer with the sets of [2, 4, 11, 3]. Just started learning programming, maybe I am missing something obvious? Thanks in advance.
8 Replies
JavaBot
JavaBot•7d ago
⌛ This post has been reserved for your question.
Hey @orbankaroly! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
JavaBot
JavaBot•7d ago
Please format your code to make it more readable. For java, it should look like this:
​`​`​`​java
public void foo() {

}
​`​`​`​
​`​`​`​java
public void foo() {

}
​`​`​`​
Peter Rader
Peter Rader•7d ago
Please tell what the method should do and what is the testcase that fails.
orbankaroly
orbankarolyOP•7d ago
you get a set of numbers and a target number, you should figure it out which two numbers of the set have the sum of the target just realised the problem was me being stupid tho 😄 forgot i can get negative numbers the way i did it
Peter Rader
Peter Rader•7d ago
oi, ye not stupid mate
orbankaroly
orbankarolyOP•7d ago
and that caused valid answers from my own sets...
Peter Rader
Peter Rader•7d ago
Please close the post if done 😄
JavaBot
JavaBot•7d ago
Post Closed
This post has been closed by <@232222326022864897>.
Want results from more Discord servers?
Add your server