My Java solution is accepted. Is it good? or may I get any hidden problems?

  • 0

    public class Solution {

    public int[] twoSum(int[] nums, int target) {
        HashMap <Integer, Integer> remainders= new HashMap<Integer, Integer>(); 

    /*make a harsh map to store the remainder, which will be (target - current value) as key, and its index as value */

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

    /* find if the current value is the remainder of the previous value or not. If true, return the previous value's index, and the current value's index */

                return new int[]{remainders.get(nums[i]), i};

    /*if cannot find the corresponding remainder, than put the current value as the key, and current index as the value into the map */

            remainders.put(target-nums[i],i );

    /* after for loop, return the empty object */

        return new int[2];


Log in to reply

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