Printing all the combination of indexes for 2 sum exact outcome












2














Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.



Input: {1,7,2,8,3,6}, 9



Output: [0, 3] [1, 2] [4, 5]



public class TwoSumExactAll {
public static void main(String args) {
int nums1 = {1,7,2,8,3,6};
for (List<Integer> list : twoSumExactWithList(nums1,9)) {
System.out.println(list);
}
}

public static ArrayList<List<Integer>> twoSumExactWithList(int nums,int target) {
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
ArrayList<Integer> innerList=null;
int complement;
for(int i=0;i<nums.length;i++) {
complement = target-nums[i];
if(map.containsKey(complement)) {
innerList = new ArrayList<Integer>();
innerList.add(map.get(complement));
innerList.add(i);
outerList.add(innerList);
}else {
map.put(nums[i], i);
}
}
return outerList;
}
}









share|improve this question
















bumped to the homepage by Community 19 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.




















    2














    Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.



    Input: {1,7,2,8,3,6}, 9



    Output: [0, 3] [1, 2] [4, 5]



    public class TwoSumExactAll {
    public static void main(String args) {
    int nums1 = {1,7,2,8,3,6};
    for (List<Integer> list : twoSumExactWithList(nums1,9)) {
    System.out.println(list);
    }
    }

    public static ArrayList<List<Integer>> twoSumExactWithList(int nums,int target) {
    HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
    ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
    ArrayList<Integer> innerList=null;
    int complement;
    for(int i=0;i<nums.length;i++) {
    complement = target-nums[i];
    if(map.containsKey(complement)) {
    innerList = new ArrayList<Integer>();
    innerList.add(map.get(complement));
    innerList.add(i);
    outerList.add(innerList);
    }else {
    map.put(nums[i], i);
    }
    }
    return outerList;
    }
    }









    share|improve this question
















    bumped to the homepage by Community 19 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


















      2












      2








      2







      Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.



      Input: {1,7,2,8,3,6}, 9



      Output: [0, 3] [1, 2] [4, 5]



      public class TwoSumExactAll {
      public static void main(String args) {
      int nums1 = {1,7,2,8,3,6};
      for (List<Integer> list : twoSumExactWithList(nums1,9)) {
      System.out.println(list);
      }
      }

      public static ArrayList<List<Integer>> twoSumExactWithList(int nums,int target) {
      HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
      ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
      ArrayList<Integer> innerList=null;
      int complement;
      for(int i=0;i<nums.length;i++) {
      complement = target-nums[i];
      if(map.containsKey(complement)) {
      innerList = new ArrayList<Integer>();
      innerList.add(map.get(complement));
      innerList.add(i);
      outerList.add(innerList);
      }else {
      map.put(nums[i], i);
      }
      }
      return outerList;
      }
      }









      share|improve this question















      Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.



      Input: {1,7,2,8,3,6}, 9



      Output: [0, 3] [1, 2] [4, 5]



      public class TwoSumExactAll {
      public static void main(String args) {
      int nums1 = {1,7,2,8,3,6};
      for (List<Integer> list : twoSumExactWithList(nums1,9)) {
      System.out.println(list);
      }
      }

      public static ArrayList<List<Integer>> twoSumExactWithList(int nums,int target) {
      HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
      ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
      ArrayList<Integer> innerList=null;
      int complement;
      for(int i=0;i<nums.length;i++) {
      complement = target-nums[i];
      if(map.containsKey(complement)) {
      innerList = new ArrayList<Integer>();
      innerList.add(map.get(complement));
      innerList.add(i);
      outerList.add(innerList);
      }else {
      map.put(nums[i], i);
      }
      }
      return outerList;
      }
      }






      java k-sum






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 11 '18 at 0:21









      200_success

      129k15152414




      129k15152414










      asked Dec 11 '18 at 0:12









      PriyankaPriyanka

      111




      111





      bumped to the homepage by Community 19 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 19 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...



          I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.



          If you choose arrays a possible return type is int where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2] is potentially more efficient than int[2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair where IntPair is a pair of ints struct-like class.



          If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.



          As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...



          I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.



          Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int nums, final int target, final Map<Integer, Integer> map, final int complement.



          I would rename map to something a bit more informative as to what it contains...
          so perhaps indexByNumValue?



          I think your code would read and look much better with some additional spaces e.g.:



          List<Integer> innerList=null; to List<Integer> innerList = null;.



          for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.



          }else { to } else {.



          if( to if (.



          nums,int to nums, int.



          etc...






          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209400%2fprinting-all-the-combination-of-indexes-for-2-sum-exact-outcome%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...



            I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.



            If you choose arrays a possible return type is int where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2] is potentially more efficient than int[2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair where IntPair is a pair of ints struct-like class.



            If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.



            As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...



            I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.



            Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int nums, final int target, final Map<Integer, Integer> map, final int complement.



            I would rename map to something a bit more informative as to what it contains...
            so perhaps indexByNumValue?



            I think your code would read and look much better with some additional spaces e.g.:



            List<Integer> innerList=null; to List<Integer> innerList = null;.



            for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.



            }else { to } else {.



            if( to if (.



            nums,int to nums, int.



            etc...






            share|improve this answer


























              0














              I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...



              I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.



              If you choose arrays a possible return type is int where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2] is potentially more efficient than int[2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair where IntPair is a pair of ints struct-like class.



              If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.



              As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...



              I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.



              Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int nums, final int target, final Map<Integer, Integer> map, final int complement.



              I would rename map to something a bit more informative as to what it contains...
              so perhaps indexByNumValue?



              I think your code would read and look much better with some additional spaces e.g.:



              List<Integer> innerList=null; to List<Integer> innerList = null;.



              for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.



              }else { to } else {.



              if( to if (.



              nums,int to nums, int.



              etc...






              share|improve this answer
























                0












                0








                0






                I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...



                I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.



                If you choose arrays a possible return type is int where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2] is potentially more efficient than int[2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair where IntPair is a pair of ints struct-like class.



                If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.



                As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...



                I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.



                Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int nums, final int target, final Map<Integer, Integer> map, final int complement.



                I would rename map to something a bit more informative as to what it contains...
                so perhaps indexByNumValue?



                I think your code would read and look much better with some additional spaces e.g.:



                List<Integer> innerList=null; to List<Integer> innerList = null;.



                for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.



                }else { to } else {.



                if( to if (.



                nums,int to nums, int.



                etc...






                share|improve this answer












                I guess that the relevant piece of code is the twoSumExactWithList method and for now I will ignore the rest...



                I think that depending on the context, e.g. the principles used in the project that you intent to use, this code you could either fully embrace collections or stick to arrays... but your code does a combo of both where the arguments are naked arrays and the returns uses collections... so please choose between the two.



                If you choose arrays a possible return type is int where one of the two dimensions is 2. representing first vs second index of the pair. In practice int[2] is potentially more efficient than int[2] but perhaps the Jit may make it irrelevant. Perhaps you could have a IntPair where IntPair is a pair of ints struct-like class.



                If you choose collections... then the arguments should be List<Integer> nums, int target. The result is kind-of fine... but don't commit to return an ArrayList but rather a List; don't give any details on the implementation that are not necessary. To encode the index pair, consider the use of a custom class IntPair again... List is correct but seems a bit overkill considering that we know is always two and exactly two elements.



                As for the method body... The varible types should be a general as they can be... so map's type should be Map<Integer, Integer> rather than HashMap<...>, outerList's should be List rather than ArrayList and so forth...



                I would declare complement within the loop as it is not used outside of it and is rewritten at every iteration. innerList would go within the if within the for.



                Whenever possible I would declare variables as final to give an extra hint to the compiler/optimizer that indeed these are not going to be changed... eg. final int nums, final int target, final Map<Integer, Integer> map, final int complement.



                I would rename map to something a bit more informative as to what it contains...
                so perhaps indexByNumValue?



                I think your code would read and look much better with some additional spaces e.g.:



                List<Integer> innerList=null; to List<Integer> innerList = null;.



                for(int i=0;i<nums.length;i++) { to for (int i = 0; i < nums.length; i++) {.



                }else { to } else {.



                if( to if (.



                nums,int to nums, int.



                etc...







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 11 '18 at 5:34









                Valentin RuanoValentin Ruano

                21613




                21613






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209400%2fprinting-all-the-combination-of-indexes-for-2-sum-exact-outcome%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    第一次世界大戦

                    Touch on Surface Book