Two Sum

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tupl…


This content originally appeared on DEV Community and was authored by OnlyLang.blogspot.com

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).

For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

Based on: http://oj.leetcode.com/problems/two-sum/

twoSum [1, 2, 3] 4 === (0, 2)

Code(Java Solution)

static int[] twoSum(int[] numbers, int target) {

         // TODO Auto-generated method stub

         int[] x = new int[2];

         for(int i=0;i<numbers.length;i++)

         {

              for(int j=0;j<numbers.length;j++)

              {

                  if(i!=j)

                  {

                       if(numbers[i]+numbers[j]==target)

                       {

                            x[0]=i;

                            x[1]=j;

                       }

                  }



              }

         }



        return x;

     }

More at : https://onlylang.blogspot.com/


This content originally appeared on DEV Community and was authored by OnlyLang.blogspot.com


Print Share Comment Cite Upload Translate Updates
APA

OnlyLang.blogspot.com | Sciencx (2022-02-03T09:03:32+00:00) Two Sum. Retrieved from https://www.scien.cx/2022/02/03/two-sum/

MLA
" » Two Sum." OnlyLang.blogspot.com | Sciencx - Thursday February 3, 2022, https://www.scien.cx/2022/02/03/two-sum/
HARVARD
OnlyLang.blogspot.com | Sciencx Thursday February 3, 2022 » Two Sum., viewed ,<https://www.scien.cx/2022/02/03/two-sum/>
VANCOUVER
OnlyLang.blogspot.com | Sciencx - » Two Sum. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/03/two-sum/
CHICAGO
" » Two Sum." OnlyLang.blogspot.com | Sciencx - Accessed . https://www.scien.cx/2022/02/03/two-sum/
IEEE
" » Two Sum." OnlyLang.blogspot.com | Sciencx [Online]. Available: https://www.scien.cx/2022/02/03/two-sum/. [Accessed: ]
rf:citation
» Two Sum | OnlyLang.blogspot.com | Sciencx | https://www.scien.cx/2022/02/03/two-sum/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.