문제로
내가 푼 것 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; for(int i = 0; i < nums.length; i++){ for(int j = 0; j < nums.length; j++){ if(i == j) continue; if(i > j) continue; if(nums[i]+nums[j] == target) { result[0] = i; result[1] = j; } } } return result; } } 답안1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n = nums.size(); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {}; // No solution found } }; 답안2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numMap = new HashMap<>(); int n = nums.length; // Build the hash table for (int i = 0; i < n; i++) { numMap.put(nums[i], i); } // Find the complement for (int i = 0; i < n; i++) { int complement = target - nums[i]; if (numMap.containsKey(complement) && numMap.get(complement) != i) { return new int[]{i, numMap.get(complement)}; } } return new int[]{}; // No solution found } } 답안3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> numMap = new HashMap<>(); int n = nums.length; for (int i = 0; i < n; i++) { int complement = target - nums[i]; if (numMap.containsKey(complement)) { return new int[]{numMap.get(complement), i}; } numMap.put(nums[i], i); } return new int[]{}; // No solution found } }