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.
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
⌛
This post has been reserved for your question.
Hey @orbankaroly! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose 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.
Please format your code to make it more readable. For java, it should look like this:
Please tell what the method should do and what is the testcase that fails.
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
oi, ye not stupid mate
and that caused valid answers from my own sets...
Please close the post if done 😄
Post Closed
This post has been closed by <@232222326022864897>.