Can someone help me optimize my code


  • 0
    Z

    My code run time of 6ms, has other faster way to do this.

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int numsSize = nums.length;
            if (numsSize < 2) {
                return new int[]{-1, -1};
            }
            HashMap<Integer, Integer> mMap = new HashMap<Integer, Integer>();
            for (int i = 0; i < numsSize; mMap.put(nums[i], ++i)) {
                if (mMap.containsKey(target - nums[i])) 
                    return new int[]{mMap.get(target - nums[i]), ++ i};
            }
            return new int[] {-1, -1};
            
        }
    }

Log in to reply
 

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