본문 바로가기
programming/알고리즘 풀이

[leetcode] 1. Two Sum

by 몽구스_ 2021. 10. 2.
728x90

 

[leetcode] 1. 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]

 

 

[코드]

1. 이중 for문 돌리기

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

 

 

2. HashMap에 차 저장하여 알맞은 차 채우기

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

 

 

댓글