lundi 21 octobre 2019

Return an integer array not working properly

I am attempting to return an array from an else statement, but it is not working.

Here is the problem I am trying to solve.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

This solution doesn't work and returns {0,10}

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == 0) return null;
        int[] numss = {0, 10};
        HashMap<Integer, Integer> s = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(s.getOrDefault(nums[i], 0) == 0) {
                s.put(target-nums[i], i);
            }
            else {
                numss[0] = i; 
                numss[1] = s.get(nums[i]);
                return numss;
            }
        }
        return numss;
    }
}

This solution works (Only change below is what the if-statement evalutates)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == 0) return null;
        int[] numss = {0, 10};
        HashMap<Integer, Integer> s = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(s.getOrDefault(nums[i], -1) == -1) {
                s.put(target-nums[i], i);
            }
            else {
                numss[0] = i; 
                numss[1] = s.get(nums[i]);
                return numss;
            }
        }
        return numss;
    }
}

This solution works

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == 0) return null;
        int[] numss = {0, 1};
        HashMap<Integer, Integer> s = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(s.getOrDefault(nums[i], -1) == -1) {
                s.put(target-nums[i], i);
            }
            else {
                numss[0] = i; 
                numss[1] = s.get(nums[i]);
                break;
            }
        }
        return numss;
    }
}

This solution works

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == 0) return null;
        HashMap<Integer, Integer> s = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(s.getOrDefault(nums[i], -1) != -1) {
                    return new int[]{ i, s.get(nums[i]) };
                }
                s.put(target - nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

Why is my else statement unable to return the array and stop the function?

Aucun commentaire:

Enregistrer un commentaire