Leetcode

[java] 1.TwoSum

Munyoung 2024. 1. 2. 16:01
public class TwoSum_1 {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        for(int i = 0; i < length; i++){
            int diff = target - nums[i]; 
            for(int j = i+1; j < length; j++){
                if(diff == nums[j]){
                    return new int[]{i,j}; 
                }
            }
        }
        return new int[]{0,0}; 
    }
}

First approach: HashMap 쓰지 않고, for loop 사용 

run time = 60ms

import java.util.HashMap; 

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

Second approach: HashMap 사용 

runtime: 4ms

 

'Leetcode' 카테고리의 다른 글

[java] 21. Merge Two Lists  (0) 2024.01.09
[java] 20. Valid Parentheses  (1) 2024.01.03