leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

처음에는 시간 복잡도가 O(n^2)으로 모든 방법을 확인해보았다.

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[i] + nums[j] == target) {
                        return new int[]{i, j};
                    }
                }
            }

            throw new IllegalArgumentException("No Answer");
        }
    }

공간 복잡도가 O(n)이지만 시간 복잡도도 O(n)으로 줄일 수 있는 방법도 있다.

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap<>();

            for (int i = 0; i < nums.length; i++) {
                int numA = target - nums[i];
                if(map.containsKey(numA)){
                    return new int[] {map.get(numA), i};
                }
                map.put(numA, i);
            }

            throw new IllegalArgumentException("No Answer");
        }
    }

 

+ Recent posts