|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
1 | 3 |
|
| 4 | +// tag renovizee |
2 | 5 | // https://github.com/DaleStudy/leetcode-study/issues/219
|
3 | 6 | // https://leetcode.com/problems/two-sum/description/
|
| 7 | + |
| 8 | +// #์๊ตฌ์ฌํญ ์์ฝ |
| 9 | +// 1. int[] nums์ int target์ด ์ฃผ์ด์ง๋ค. |
| 10 | +// 2. nums์ ๋ ์์ ํฉ์ด target๊ณผ ๊ฐ์ int[] index๋ฅผ ๋ฆฌํดํ๋ค. (์์ ์๊ด x) |
| 11 | +// 3. ๋๊ฐ์ ์์๋ฅผ ๋๋ฒ ์ฌ์ฉํ์ง ๋ชปํ๊ณ , ์ ํํ ํ๋์ ์ ๋ต๋ง ์๋ค. |
| 12 | + |
4 | 13 | class Solution {
|
| 14 | + // Solv2: map |
| 15 | + // ์๊ฐ๋ณต์ก๋ : O(n) |
| 16 | + // ๊ณต๊ฐ๋ณต์ก๋ : O(1) |
5 | 17 | public int[] twoSum(int[] nums, int target) {
|
6 |
| - int[] result = {11, 2}; |
| 18 | + Map<Integer, Integer> map = new HashMap<>(); |
| 19 | + int[] result = new int[2]; |
| 20 | + for (int i = 0; i < nums.length; i++) { |
| 21 | + map.put(nums[i], i); |
| 22 | + } |
7 | 23 |
|
| 24 | + for (int i = 0; i < nums.length; i++) { |
| 25 | + int key = target - nums[i]; |
| 26 | + if (map.containsKey(key) && map.get(key) != i) { |
| 27 | + result[0] = i; |
| 28 | + result[1] = map.get(key); |
| 29 | + } |
| 30 | + } |
8 | 31 | return result;
|
9 | 32 |
|
10 | 33 | }
|
| 34 | +//------------------------------------------------------------------------------------------------------------- |
| 35 | +// Solv1: Brute Force |
| 36 | +// ์๊ฐ๋ณต์ก๋ : O(n^2) |
| 37 | +// ๊ณต๊ฐ๋ณต์ก๋ : O(1) |
| 38 | +// public int[] twoSum(int[] nums, int target) { |
| 39 | +// int size = nums.length; |
| 40 | +// for(int i = 0; i < size - 1; i++) { |
| 41 | +// for(int j = i+1; j < size; j++) { |
| 42 | +// if(target == (nums[i] + nums[j])){ |
| 43 | +// return new int[]{i,j}; |
| 44 | +// } |
| 45 | +// } |
| 46 | +// } |
| 47 | +// return new int[]{}; |
| 48 | +// } |
| 49 | +//------------------------------------------------------------------------------------------------------------- |
| 50 | +// ๊ธฐ๋ณธ ๋ฌธ๋ฒ ํผ๋๋ฐฑ (์ค๋๋ง์ด๋ผ..๊ฐ์ ํ์) |
| 51 | +// 1) ==: ๋ ๊ฐ์ด ๊ฐ์์ง ๋น๊ต. ๊ธฐ๋ณธ ํ์
์ ๊ฐ์ ๋น๊ตํ๊ณ , ์ฐธ์กฐ ํ์
์ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์(๋์ผํ ๊ฐ์ฒด์ธ์ง)๋ฅผ ๋น๊ต |
| 52 | +// ์ฐธ์กฐ ํ์
๊ฐ์ฒด์ ๋ด์ฉ์ด ๊ฐ์์ง๋ฅผ ๋น๊ตํ๋ ค๋ฉด ์ฃผ๋ก a.equals(b)๋ฅผ ์ฌ์ฉ |
| 53 | +// |
| 54 | +// 2) ์ด๊ธฐํ ๋ฐฐ์ด๊ณผ ๋งต |
| 55 | +// - new int[2] :size ์ด๊ธฐํ |
| 56 | +// - new int[]{1,2,3} : ์ค์ ๊ฐ ์ด๊ธฐํ |
| 57 | +// - Map<String,String> test = new HashMap<>(); ๋งต์ k/v ํ์
์ ์ ๋ณ์์ ์ค์ ํ๋ค. val ๋ง์ฌ์ฉํ๋ค.. |
| 58 | +//------------------------------------------------------------------------------------------------------------- |
| 59 | + |
11 | 60 | }
|
0 commit comments