Java O(n) and a question

  • 0

    So this is my first time using Java, and I came up with this:

    class Solution {
        public static int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
            for(int i = 0; i < nums.length; i++){
                int val = nums[i];
                int targetVal = target - val;
                Integer targetIndex = hash.get(val);
                if(targetIndex != null){
                  return new int[]{targetIndex, i};
                hash.put(targetVal, i);
        return null;

    My question is this: Most of the solutions I see utilize containsKey, and then use a get when they want the value. My understanding is that containsKey performs a get and throws away the value. I know this is a very minor thing but why would you not do a get and then null check to avoid having to go to the map in succession?

Log in to reply

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