Post

๐Ÿ’ก LeetCode 1 - Two Sum

๐Ÿ’ก LeetCode 1 - Two Sum

๋ฌธ์ œ

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.

์ž…์ถœ๋ ฅ ์˜ˆ์ œ

โœ… ์˜ˆ์ œ 1

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

โœ… ์˜ˆ์ œ 2

1
2
Input: nums = [3,2,4], target = 6
Output: [1,2]

โœ… ์˜ˆ์ œ 3

1
2
Input: nums = [3,3], target = 6
Output: [0,1]

์ œ์•ฝ์กฐ๊ฑด

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

์ž‘์„ฑ ์ฝ”๋“œ

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 arrLength = nums.length;
		int[] result = new int[2];
		for (int i=0; i<arrLength; i++) {
			for (int j=i+1; j<arrLength; j++) {
				if (nums[i] + nums[j] == target) {
					result[0] = i;
					result[1] = j;
					break;
				}
			}
		}
		return result;
	}
}

  • ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค๋ณด๋‹ค ์†๋„๊ฐ€ ๊ต‰์žฅํžˆ ๋‚ฎ์•„์„œ ๊ฐœ์„ ํ•ด๋ณด๊ณ ์ž ํ•œ๋‹ค.

๊ฐœ์„  ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
	public int[] twoSum(int[] nums, int target) {
		// 1. ๋ณ€์ˆ˜ ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”
		Map<Integer, Integer> idxMap = new HashMap<>();
		int[] result = new int[2];
		
		// 2. ์ˆœํšŒํ•˜๋ฉฐ ๋‘ ๊ฐ’์˜ ํ•ฉ์ด target์ธ ๊ฒฝ์šฐ ํƒ์ƒ‰
		int idx = 0;
		for (int num : nums) {
			// ํ•ด๋‹น ์›์†Œ ํ‚ค ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ๋ฐ˜ํ™˜
			if (idxMap.containsKey(num)) result = new int[] { idxMap.get(num), idx };
			
			// target - nums[idx]์™€ idx์˜ ํ‚ค-๊ฐ’์Œ ์ €์žฅ
			int theOtherNum = target - nums[idx];
			idxMap.put(theOtherNum, idx);
			
			// ์ธ๋ฑ์Šค ์ฆ๊ฐ€
			idx++;
		}
		
		// 3. ๋ฐ˜ํ™˜
		return result;
	}
}

  • ์ด์ค‘ for๋ฌธ์ด ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ๋‹จ์ผ for๋ฌธ๊ณผ ํ•จ๊ป˜ HashMap์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค.
  • ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ํ˜„์žฌ ๊ฐ’์ด ์ด์ „ ๊ฐ’๋“ค์˜ target - nums[idx]์— ํ•ด๋‹นํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

ํšŒ๊ณ 

  • ๋” ๋น ๋ฅด๊ฒŒ ํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ•  ์ง€ ๊ถ๊ธˆํ•˜๋‹ค.
This post is licensed under CC BY 4.0 by the author.