MY Java Solution - a bit heavy


  • 0
    H
    import java.util.*;
    
    class Solution {
        static int[] twoSum(int[] nums, int target) {
            ArrayList<Integer> list = new ArrayList<>();
            ArrayList<Integer> originalList = new ArrayList<>();
    
            for (int i = 0; i < nums.length; i++)
            {
                list.add(nums[i]);
            }
            originalList = (ArrayList) list.clone();
    
            Collections.sort(list);
    
            return seekingNumbers(list, target, originalList);
        }
    
        /**
         * Introduce a method to recursively getting the two numbers at the very beginning and end of the list, and compare with the target
         * 
         * @param list
         * @param target
         * @param originalList
         * @return
         */
        private static int[] seekingNumbers(ArrayList list, int target, ArrayList originalList){
           int[] result = new int[2];
            if (list.size() == 1){
                return result;
            }
            int firstValue = ((Integer)list.get(0)).intValue();
    
            if (firstValue >= target) {
                return result;
            }
    
            int lastValue = ((Integer)list.get(list.size() - 1)).intValue();
            int sum = firstValue + lastValue;
            if (sum == target){
                result[0] = originalList.indexOf(firstValue);
                result[1] = originalList.indexOf(lastValue);
                return result;
            } else if (sum < target){
                list.remove(0);
                return seekingNumbers(list, target, originalList);
            } else if (sum > target){
                list.remove(list.size() - 1);
                return seekingNumbers(list, target, originalList);
            } else {
                return result;
            }
        }
    }
    

    when I submit the code, it says stackoverflowerror. while I put it down my local and see the error happens in

    else if (sum > target){
                list.remove(list.size() - 1);
                seekingNumbers(list, target, originalList);
            } 
    

    It only happens when the nums size is bit bigger (on my local, it is 5622).
    Can anyone help out why is that? Thank you.

    Jimmy


  • 0
    H

    Knew what was happening, it is actually "overflow" because the stack size if not big enough for the 10000 times recursion.

    New to java, good to know it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.