[LeetCode] Two Sum 풀이

완전탐색

  • 시간복잡도 O(N^2)
  • 공간복잡도 O(1)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    return new int[]{i, j};
                }
            }
        }

        return new int[]{};
    }
}

 

HashTable

  • 시간 복잡도 O(N)
  • 공간 복잡도 O(N)
import java.util.*;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            int key = target - nums[i];
            if (map.get(key) != null) {
                int value = map.get(key);

                if (value < i) {
                    return new int[]{value, i};
                } else {
                    return new int[]{i, value};
                }
                
            } else {
                map.put(nums[i], i);
            }
        }

        return new int[]{};
    }
}

'Algorithms > 문제풀이' 카테고리의 다른 글

[LeetCode] Valid Parentheses 풀이  (0) 2024.09.03
[LeetCode] Roman to Integer 풀이  (2) 2024.09.02
[LeetCode] Palindrome Number 풀이  (0) 2024.08.27
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유