Improve efficiency on the accepted solution


  • 0
    V

    19 test cases passed for my code below.. however, needs to improve efficiency for larger arrays. Please suggest what changes can be made to improve efficiency.

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int size = nums.length;
            int result[] = new int[2];
            List<Integer> numsList = Arrays.stream(nums).boxed().collect(Collectors.toList());
            for(int i = 0; i < size; i++) {
                int itemToFound = target - nums[i];
                int itemToFoundIndex = numsList.indexOf(itemToFound);
                if (itemToFoundIndex != i && numsList.contains(itemToFound)) {
                    result[0] = i;
                    result[1] = itemToFoundIndex;
                }
            }
            Arrays.sort(result);
            return result;
        }
    }
    

Log in to reply
 

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