[Leetcode]1. Two Sum

2024. 7. 30. 21:36java/javaAlgorithm

1. problem : 

https://leetcode.com/problems/two-sum/description/

 

2. solution 1 :

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

시간복잡도는 O(n)이다. hashMap을 이용하는데, target - char가 없다면 nums [i] 등록, diff가 있다면 index 반환 

'java > javaAlgorithm' 카테고리의 다른 글

[Leetcode]49. Group Anagrams(x)  (0) 2024.07.31
[Leetcode]15. 3Sum(x)  (0) 2024.07.30
[Leetcode]242. Valid Anagram  (0) 2024.07.30
[Leetcode]217. Contains Duplicate  (0) 2024.07.30
[Leetcode]3146. Permutation Difference between Two Strings  (0) 2024.07.30